5 kinds of gestures Spring Boot mail sent!

Send e-mail is actually a very common requirement, user registration, password recovery and other places, will be used to send mail using JavaSE code step was quite cumbersome, Spring Boot in the e-mail sent, provides automated configuration related classes, making it very easy to send e-mail this article we take a closer look! Look at using Spring Boot to send mail 5 position.

Messaging Infrastructure

We often hear various mail protocols, such as SMTP, POP3, IMAP, then what is the role of these agreements, what is the difference? We first discuss the issue.

SMTP is a TCP / IP based application layer protocol, established position somewhat similar to HTTP, SMTP server listens on the default port number is 25. See here, little friends might think since SMTP protocol is based on TCP / IP application layer protocol, so I can not send a message through the Socket it? The answer is yes.

Life we ​​deliver a message to go through the following steps:

  1. Shenzhen Wang first deliver mail to the post office in Shenzhen
  2. Shenzhen post office mail delivery to the post office in Shanghai
  3. Shanghai's Zhang to the post office mailing

This is a scaled-down version of life in the mailing process. These three steps may correspond to an email sending process is assumed to transmit messages from [email protected] [email protected]:

  1. [email protected] first mail delivery to Tencent's mail server
  2. Tencent mail server will deliver mail to our mail server NetEase
  3. [email protected] login Netease mail server to view e-mail

Mail delivery generally is this process that will involve more than one protocol, let's look at each.

SMTP protocol called the Simple Mail Transfer Protocol, translated as Simple Mail Transfer Protocol, which defines between mail client and SMTP server, and communication rules between the SMTP server and SMTP server.

That [email protected] user first mail delivery to the SMTP server Tencent This process uses the SMTP protocol, then Tencent's SMTP server to deliver mail to the SMTP server NetEase This process is still using the SMTP protocol, SMTP server It is used to receive mail.

The POP3 protocol called the Post Office Protocol, translated as Post Office Protocol, which defines the rules of communication between the client and the POP3 mail server, then the agreement will be used in what scene it? When a message arrives NetEase's SMTP server, [email protected] users need to log in to view the e-mail server, this time on the agreement to use it: e-mail service provider will provide each user a dedicated space for message store, SMTP server receives after the message, the message will be saved to the user's mail storage space, if you want to read mail, you need to be done by mail service provider POP3 mail server.

Finally, there may be little friends heard of IMAP protocol, which is an extension to the POP3 protocol, more powerful, similar to the role, not repeat them here.

Ready to work

At present, most of the direct mail service providers are not allowed to send messages in code using a username / password way, all must first apply for an authorization code, here to QQ mailbox as an example, we demonstrate to the authorization code application process: First we need to be logged in the web version of QQ mailbox, click the settings button at the top:

Then click on the Account tab:

Find open POP3 / SMTP option in the Account tab, as follows:

Click on, to open related functions, open process requires phone verification number, follow the steps to not repeat them. After a successful open, you can obtain an authorization code, save the number, one will use.

Project Creation

Next, we can create a project, Spring Boot, the e-mail sent provides automatic configuration class, developers only need to add its dependencies, and then configure the basic information about the mailbox, you can send mail.

  • First create a Spring Boot project, the introduction of e-mail sent dependence:

Once created, the project relies as follows:

<dependency>
    <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
  • Configure Mailbox Basic information

After the project is successfully created, the following basic configuration information in a mailbox in application.properties:

spring.mail.host=smtp.qq.com
spring.mail.port=587
spring.mail.username=1510161612@qq.com
spring.mail.password=ubknfzhjkhrbbabe
spring.mail.default-encoding=UTF-8 spring.mail.properties.mail.smtp.socketFactoryClass=javax.net.ssl.SSLSocketFactory spring.mail.properties.mail.debug=true

Configuring meanings are as follows:

  • Configure the SMTP server address
  • SMTP server port
  • Configure mailbox user name
  • Configuration password, note, not the real password, but just apply to the authorization code
  • The default message encoding
  • Accessories SSL encryption factory
  • Indicate on DEBUG mode, so that the process of log messages sent will be printed in the console, easy to troubleshoot error

If you do not know the words or the address of the smtp server port, refer to Tencent's mailbox documents

  • https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=371

做完这些之后,Spring Boot 就会自动帮我们配置好邮件发送类,相关的配置在 org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration 类中,部分源码如下:

@Configuration
@ConditionalOnClass({ MimeMessage.class, MimeType.class, MailSender.class })
@ConditionalOnMissingBean(MailSender.class)
@Conditional(MailSenderCondition.class)
@EnableConfigurationProperties(MailProperties.class) @Import({ MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class }) public class MailSenderAutoConfiguration { }

从这段代码中,可以看到,导入了另外一个配置 MailSenderPropertiesConfiguration 类,这个类中,提供了邮件发送相关的工具类:

@Configuration
@ConditionalOnProperty(prefix = "spring.mail", name = "host")
class MailSenderPropertiesConfiguration { private final MailProperties properties; MailSenderPropertiesConfiguration(MailProperties properties) { this.properties = properties; } @Bean @ConditionalOnMissingBean public JavaMailSenderImpl mailSender() { JavaMailSenderImpl sender = new JavaMailSenderImpl(); applyProperties(sender); return sender; } }

可以看到,这里创建了一个 JavaMailSenderImpl 的实例, JavaMailSenderImplJavaMailSender 的一个实现,我们将使用 JavaMailSenderImpl 来完成邮件的发送工作。

做完如上两步,邮件发送的准备工作就算是完成了,接下来就可以直接发送邮件了。

具体的发送,有 5 种不同的方式,我们一个一个来看。

发送简单邮件

简单邮件就是指邮件内容是一个普通的文本文档:

@Autowired
JavaMailSender javaMailSender;
@Test
public void sendSimpleMail() { SimpleMailMessage message = new SimpleMailMessage(); message.setSubject("这是一封测试邮件"); message.setFrom("[email protected]"); message.setTo("[email protected]"); message.setCc("[email protected]"); message.setBcc("[email protected]"); message.setSentDate(new Date()); message.setText("这是测试邮件的正文"); javaMailSender.send(message); }

从上往下,代码含义分别如下:

  1. 构建一个邮件对象
  2. 设置邮件主题
  3. 设置邮件发送者
  4. 设置邮件接收者,可以有多个接收者
  5. 设置邮件抄送人,可以有多个抄送人
  6. 设置隐秘抄送人,可以有多个
  7. 设置邮件发送日期
  8. 设置邮件的正文
  9. 发送邮件

最后执行该方法,就可以实现邮件的发送,发送效果图如下:

发送带附件的邮件

邮件的附件可以是图片,也可以是普通文件,都是支持的。

@Test
public void sendAttachFileMail() throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true); helper.setSubject("这是一封测试邮件"); helper.setFrom("[email protected]"); helper.setTo("[email protected]"); helper.setCc("[email protected]"); helper.setBcc("[email protected]"); helper.setSentDate(new Date()); helper.setText("这是测试邮件的正文"); helper.addAttachment("javaboy.jpg",new File("C:\\Users\\sang\\Downloads\\javaboy.png")); javaMailSender.send(mimeMessage); }

注意这里在构建邮件对象上和前文有所差异,这里是通过 javaMailSender 来获取一个复杂邮件对象,然后再利用 MimeMessageHelper 对邮件进行配置,MimeMessageHelper 是一个邮件配置的辅助工具类,创建时候的 true 表示构建一个 multipart message 类型的邮件,有了 MimeMessageHelper 之后,我们针对邮件的配置都是由 MimeMessageHelper 来代劳。

最后通过 addAttachment 方法来添加一个附件。

执行该方法,邮件发送效果图如下:

发送带图片资源的邮件

图片资源和附件有什么区别呢?图片资源是放在邮件正文中的,即一打开邮件,就能看到图片。但是一般来说,不建议使用这种方式,一些公司会对邮件内容的大小有限制(因为这种方式是将图片一起发送的)。

@Test
public void sendImgResMail() throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setSubject("这是一封测试邮件"); helper.setFrom("[email protected]"); helper.setTo("[email protected]"); helper.setCc("[email protected]"); helper.setBcc("[email protected]"); helper.setSentDate(new Date()); helper.setText("<p>hello 大家好,这是一封测试邮件,这封邮件包含两种图片,分别如下</p><p>第一张图片:</p><img src='cid:p01'/><p>第二张图片:</p><img src='cid:p02'/>",true); helper.addInline("p01",new FileSystemResource(new File("C:\\Users\\sang\\Downloads\\javaboy.png"))); helper.addInline("p02",new FileSystemResource(new File("C:\\Users\\sang\\Downloads\\javaboy2.png"))); javaMailSender.send(mimeMessage); }

这里的邮件 text 是一个 HTML 文本,里边涉及到的图片资源先用一个占位符占着,setText 方法的第二个参数 true 表示第一个参数是一个 HTML 文本。

setText 之后,再通过 addInline 方法来添加图片资源。

最后执行该方法,发送邮件,效果如下:

在公司实际开发中,第一种和第三种都不是使用最多的邮件发送方案。因为正常来说,邮件的内容都是比较的丰富的,所以大部分邮件都是通过 HTML 来呈现的,如果直接拼接 HTML 字符串,这样以后不好维护,为了解决这个问题,一般邮件发送,都会有相应的邮件模板。最具代表性的两个模板就是 Freemarker 模板和 Thyemeleaf 模板了。

使用 Freemarker 作邮件模板

首先需要引入 Freemarker 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>

然后在 resources/templates 目录下创建一个 mail.ftl 作为邮件发送模板:

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>hello 欢迎加入 xxx 大家庭,您的入职信息如下:</p> <table border="1"> <tr> <td>姓名</td> <td>${username}</td> </tr> <tr> <td>工号</td> <td>${num}</td> </tr> <tr> <td>薪水</td> <td>${salary}</td> </tr> </table> <div style="color: #ff1a0e">一起努力创造辉煌</div> </body> </html>

接下来,将邮件模板渲染成 HTML ,然后发送即可。

@Test
public void sendFreemarkerMail() throws MessagingException, IOException, TemplateException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setSubject("这是一封测试邮件"); helper.setFrom("[email protected]"); helper.setTo("[email protected]"); helper.setCc("[email protected]"); helper.setBcc("[email protected]"); helper.setSentDate(new Date()); //构建 Freemarker 的基本配置 Configuration configuration = new Configuration(Configuration.VERSION_2_3_0); // 配置模板位置 ClassLoader loader = MailApplication.class.getClassLoader(); configuration.setClassLoaderForTemplateLoading(loader, "templates"); //加载模板 Template template = configuration.getTemplate("mail.ftl"); User user = new User(); user.setUsername("javaboy"); user.setNum(1); user.setSalary((double) 99999); StringWriter out = new StringWriter(); //模板渲染,渲染的结果将被保存到 out 中 ,将out 中的 html 字符串发送即可 template.process(user, out); helper.setText(out.toString(),true); javaMailSender.send(mimeMessage); }

需要注意的是,虽然引入了 Freemarker 的自动化配置,但是我们在这里是直接 new Configuration 来重新配置 Freemarker 的,所以 Freemarker 默认的配置这里不生效,因此,在填写模板位置时,值为 templates

调用该方法,发送邮件,效果图如下:

使用 Thymeleaf 作邮件模板

推荐在 Spring Boot 中使用 Thymeleaf 来构建邮件模板。因为 Thymeleaf 的自动化配置提供了一个 TemplateEngine,通过 TemplateEngine 可以方便的将 Thymeleaf 模板渲染为 HTML ,同时,Thymeleaf 的自动化配置在这里是继续有效的 。

首先,引入 Thymeleaf 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>

然后,创建 Thymeleaf 邮件模板:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>hello 欢迎加入 xxx 大家庭,您的入职信息如下:</p> <table border="1"> <tr> <td>姓名</td> <td th:text="${username}"></td> </tr> <tr> <td>工号</td> <td th:text="${num}"></td> </tr> <tr> <td>薪水</td> <td th:text="${salary}"></td> </tr> </table> <div style="color: #ff1a0e">一起努力创造辉煌</div> </body> </html>

接下来发送邮件:

@Autowired
TemplateEngine templateEngine;

@Test
public void sendThymeleafMail() throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setSubject("这是一封测试邮件"); helper.setFrom("[email protected]"); helper.setTo("[email protected]"); helper.setCc("[email protected]"); helper.setBcc("[email protected]"); helper.setSentDate(new Date()); Context context = new Context(); context.setVariable("username", "javaboy"); context.setVariable("num","000001"); context.setVariable("salary", "99999"); String process = templateEngine.process("mail.html", context); helper.setText(process,true); javaMailSender.send(mimeMessage); }

调用该方法,发送邮件,效果图如下:

好了,这就是我们今天说的 5 种邮件发送姿势,不知道你掌握了没有呢?

本文案例已经上传到 GitHub:https://github.com/lenve/javaboy-code-samples

有问题欢迎留言讨论。

关注公众号【江南一点雨】,专注于 Spring Boot+微服务以及前后端分离等全栈技术,定期视频教程分享,关注后回复 Java ,领取松哥为你精心准备的 Java 干货!

Guess you like

Origin www.cnblogs.com/xichji/p/11199185.html