Sending Emails with Java – 用Java发送邮件

最后修改: 2018年 4月 29日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’re going to look at sending an email with and without attachments using the core Java mail library.

在这个快速教程中,我们将看看如何使用核心Java邮件库发送带附件和不带附件的电子邮件。

2. Project Setup and Dependency

2.项目设置和依赖性

For this article, we’ll be using a simple Maven-based project with a dependency on the Java mail library:

在本文中,我们将使用一个简单的基于Maven的项目,该项目对Java邮件库有依赖性。

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.5.0-b01</version>
</dependency>

The latest version can be found here.

最新版本可以在这里找到。

3. Sending a Plain Text and an HTML Email

3.发送纯文本和HTML邮件

First, we need to configure the library with our email service provider’s credentials. Then we’ll create a Session that’ll be used in constructing our message for sending.

首先,我们需要用我们的电子邮件服务提供商的凭据来配置库。然后,我们将创建一个Session,用于构建我们的邮件发送。

The configuration is via a Java Properties object:

配置是通过一个JavaProperties对象进行的。

Properties prop = new Properties();
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", "smtp.mailtrap.io");
prop.put("mail.smtp.port", "25");
prop.put("mail.smtp.ssl.trust", "smtp.mailtrap.io");

In the properties configuration above, we configured the email host as Mailtrap and used the port provided by the service as well.

在上面的属性配置中,我们把电子邮件主机配置为Mailtrap,并且也使用了该服务提供的端口。

Now let’s create a session with our username and password:

现在让我们用我们的用户名和密码创建一个会话。

Session session = Session.getInstance(prop, new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
});

The username and password are given by the mail service provider alongside the host and port parameters.

用户名和密码是由邮件服务提供者提供的,同时还有主机和端口参数。

Now that we have a mail Session object, let’s create a MimeMessage for sending:

现在我们有了一个邮件Session对象,让我们创建一个MimeMessage用于发送。

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@gmail.com"));
message.setRecipients(
  Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
message.setSubject("Mail Subject");

String msg = "This is my first email using JavaMailer";

MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html; charset=utf-8");

Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);

message.setContent(multipart);

Transport.send(message);

In the snippet above, we first created a message instance with the necessary properties — to, from and subject. This is followed by a mimeBodyPart that has an encoding of text/html since our message is styled in HTML.

在上面的片段中,我们首先创建了一个messageinstance,它具有必要的属性–收件人、发件人和主题。接下来是一个mimeBodyPart,其编码为text/html,因为我们的消息是以HTML为风格的。

Next, we created an instance of MimeMultipart object that we can use to wrap the mimeBodyPart we created.

接下来,我们创建了一个MimeMultipart对象的实例,我们可以用它来包装我们创建的mimeBodyPart

Finally, we set the multipart object as the content of our message and used the send() of Transport object to do the mail sending.

最后,我们将multipart对象设置为我们的message内容,并使用Transport对象的send() 来完成邮件发送。

So, we can say that the mimeBodyPart is contained in the multipart that is contained in the message. This way, a multipart can contain more than one mimeBodyPart.

因此,我们可以说mimeBodyPart包含在multipart中,而message中也包含了该部分。这样一来,一个multipart可以包含一个以上的mimeBodyPart

This is going to be the focus of the next section.

这将是下一节的重点。

4. Sending Email With an Attachment

4.发送带有附件的电子邮件

Next, to send an attachment, we only need to create another MimeBodyPart and attach the file(s) to it:

接下来,要发送一个附件,我们只需要创建另一个MimeBodyPart并将文件附加到其中。

MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.attachFile(new File("path/to/file"));

We can then add the new body part to the MimeMultipart object we created earlier:

然后我们可以将新的主体部分添加到我们之前创建的MimeMultipart对象中。

multipart.addBodyPart(attachmentBodyPart);

That’s all we need to do.

这就是我们需要做的一切。

Once again, we set the multipart instance as the content of the message object, and finally we’ll use the send() to do the mail sending.

再一次,我们将multipartinstance设置为message对象的内容,最后我们将使用send() 来完成邮件发送。

5. Formatting Email Text

5.格式化电子邮件文本

To format and style our email text, we can use HTML and CSS tags.

要对我们的电子邮件文本进行格式化和风格化,我们可以使用HTML和CSS标签。

For example, if we want our text to be bold, we will implement the <b> tag. For coloring the text, we can use the style tag. We can also combine HTML tags with CSS tags if we want to have additional properties, such as bold.

例如,如果我们希望我们的文本是粗体的,我们将实现<b>tag。对于给文本着色,我们可以使用style标签。如果我们想拥有额外的属性,如粗体,我们也可以将HTML标签与CSS标签结合起来。

Let’s create a String containing bold-red text:

让我们创建一个包含粗体红色文本的String

String msgStyled = "This is my <b style='color:red;'>bold-red email</b> using JavaMailer";

This String will hold our styled text to be sent in the email body.

这个字符串将容纳我们的风格化文本,并在电子邮件正文中发送。

6. Conclusion

6.结论

In this article, we’ve seen how to use the native Java mail library to send emails even with attachments.

在这篇文章中,我们已经看到了如何使用本地的Java邮件库来发送邮件,甚至是带附件的邮件。

As always, the complete source code is available over on GitHub.

一如既往,完整的源代码可在GitHub上获得