spring boot (X) - E-mail Example

Send e-mail summary of blog

Foreword

In fact, sending mail is a relatively simple operation, but did not summarize before, summarized here, divided into four categories: 1, sending simple text messages. 2, send messages with attachments. 3, send a message with HTML links. 4, send e-mail template rendering.

Ready to work

Throughout it would be, for example, and to complete the examples by themselves for the way e-mail to QQ-mail, for example. Preparatory work needs to be done is actually divided into two, one is to import program configuration and the other is to open its own SMTP mail services.

Open SMTP service

1, into their own mailbox, and then locate the Settings button
Here Insert Picture Description
2, enter the account tab

Here Insert Picture Description

3, and then find the option following the opening of POP3 / SMTP services

Here Insert Picture Description

I have been here is opened, if the need to open, also need to click on the following authorization code, and then configure authorization code into your local file, and then click the Save Settings page, get.

The introduction of relevant configuration

1, the introduction of mail service depends

<!--email-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2, the introduction of the e-mail configuration

##发送邮件的配置信息
spring.mail.host=smtp.qq.com
spring.mail.port=587	//相关端口,这个
spring.mail.username=********* //这里配置自己的邮件用户名
spring.mail.password=********* //这里就是配置的授权码
spring.mail.protocol=smtp
spring.mail.needAuth=true
spring.mail.sslClass=javax.net.ssl.SSLSocketFactory	//指定加密认证方式

At this point we are ready to do all the work, you can start a specific instance

Send simple text messages

Once configured, the service directly on their own definition of the class, the injection JavaMailSender on it, ready to paste the code here

@Autowired
private JavaMailSender mailSender;

/**
 * 发送简单的文本消息邮件
 *
 * @param subject 邮件主题
 * @param content 邮件内容
 * @param tos     目的邮箱(可以多个)
 */
public void sendSimpleMail(final String subject, final String content, final String[] tos) {
    SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
    //这里写在配置文件中了,这里应该指定自己的邮件服务器的账户
    simpleMailMessage.setFrom(environment.getProperty("mail.send.from")); //指定那个人发的
    simpleMailMessage.setTo(tos); //指定邮件发往何处
    simpleMailMessage.setSubject(subject); //指定发送邮件的主题
    simpleMailMessage.setText(content);
    mailSender.send(simpleMailMessage);
    log.info("简单文本邮件发送成功:{}", simpleMailMessage);

}

controller test code

@RequestMapping(value = prefix + "/send/simple", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public BaseResponse sendSimpleMail(@RequestBody @Validated MailRequest mailRequest, BindingResult bindingResult) {
    BaseResponse response = new BaseResponse(StatusCode.Success);
    try {
        String checkResult = ValidatorUtils.checkResult(bindingResult);
        if (StringUtils.isNotBlank(checkResult)) {
            return new BaseResponse(StatusCode.Invalid_Params);
        }
        log.info("发送简单文本邮件参数为:{}", mailRequest);
        String[] mailTos = StringUtils.split(mailRequest.getMailTos(), ",");
		//只需要关注这个就可以,这个就是调用service的发送邮件
        mailService.sendSimpleMail(mailRequest.getSubject(), mailRequest.getContent(), mailTos);
    } catch (Exception e) {
        response = new BaseResponse(StatusCode.Fail);
        log.error("发送邮件异常:{}", e);
    }
    return response;
}

Send mail with attachments

Send a message with an attachment file, you need to configure the file attachment address

#附件文件的文件夹地址
mail.send.attachment.location.root.url=D:\\MailAttachment

##第一个附件文件的文件名和文件地址
mail.send.attachment.one.location=${mail.send.attachment.location.root.url}\\image1.jpg
mail.send.attachment.one.name=图片1.jpg

##第二个附件文件的文件名和文件地址
mail.send.attachment.two.location=${mail.send.attachment.location.root.url}\\image2.jpg
mail.send.attachment.two.name=图片2.jpg

##第三个附件文件的文件名和文件地址,这里故意将文件名弄的有点长
mail.send.attachment.three.location=${mail.send.attachment.location.root.url}\\SpringBoot邮件测试发送附件文件.docx
mail.send.attachment.three.name=SpringBoot邮件测试发送附件文件测试长文件名称的文件附件这个文件的文件名字就是怎么长不要怀疑.docx

After configuration, in the example may be utilized MimeMessageHelperto construct complete formal message to be sent, the specific code as follows:

    /**
     * 发送带有附件的邮件
     *
     * @param subject
     * @param content
     * @param tos
     */
    public void sendAttachmentMail(final String subject, final String content, final String[] tos) throws Exception {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //这里如果要发送附件,需要将第二个参数置为true,将邮件信息对象切换到多模块模式。
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        messageHelper.setFrom(environment.getProperty("mail.send.from"));
        messageHelper.setTo(tos);
        messageHelper.setSubject(subject);
        //加入简单文本消息
        messageHelper.setText(content);
        //加入附件文件
        messageHelper.addAttachment(environment.getProperty("mail.send.attachment.one.name"), new File(environment.getProperty("mail.send.attachment.one.location")));
        messageHelper.addAttachment(environment.getProperty("mail.send.attachment.two.name"), new File(environment.getProperty("mail.send.attachment.two.location")));
        messageHelper.addAttachment(environment.getProperty("mail.send.attachment.three.name"), new File(environment.getProperty("mail.send.attachment.three.location")));

        mailSender.send(mimeMessage);
        log.info("发送带附件的邮件成功:{}", mimeMessage);

    }

controller test file

/**
 * 发送带附件的邮件
 *
 * @param mailRequest
 * @param bindingResult
 * @return
 */
@RequestMapping(value = prefix + "/send/attachment", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public BaseResponse sendAttachmentMail(@RequestBody @Validated MailRequest mailRequest, BindingResult bindingResult) {
    BaseResponse response = new BaseResponse(StatusCode.Success);
    try {
        String checkResult = ValidatorUtils.checkResult(bindingResult);
        if (StringUtils.isNotBlank(checkResult)) {
            return new BaseResponse(StatusCode.Invalid_Params);
        }
        log.info("开始发送带有附件的邮件:{}", mailRequest);
        String[] mailTos = StringUtils.split(mailRequest.getMailTos(), ",");
		
		//只需要关注这里就好
        mailService.sendAttachmentMail(mailRequest.getSubject(), mailRequest.getContent(), mailTos);
    } catch (Exception e) {
        response = new BaseResponse(StatusCode.Fail);
        log.error("发送带附件的邮件异常,异常信息为:{}", e);
    }
    return response;
}

The end result, you will find the results received there would be a problem

Here Insert Picture Description

The third document file name is too long, the direct garbled, and this embarrassment, and finally by finding the source (I have forgotten why I find the) found that, in fact, there is a default attribute is opened, resulting in file name length more than 60, it will automatically segmentation, it is necessary at startup to turn off this attribute, as shown below:

/**
 * 如果附件中指示的文件名过长,则会出现文件乱码的问题,是因为默认的属性
 * mail.mime.splitlongparameters=true所致,这里需要将其置为false
 */
@PostConstruct
public void init() {
    System.setProperty("mail.mime.splitlongparameters", "false");
}

After the test results are normal

Send a message with HTML text

This need only modify a parameter before it on the basis of

/**
 * 发送HTML类型的邮件
 *
 * @param subject
 * @param content
 * @param tos
 */
public void sendHTMLMail(final String subject, final String content, final String[] tos) throws Exception {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
    messageHelper.setFrom(environment.getProperty("mail.send.from"));
    messageHelper.setTo(tos);
    messageHelper.setSubject(subject);
    log.info(content);
    messageHelper.setText(content, true);//第二个参数设置为true,表示为发送HTML文本

    messageHelper.addAttachment(environment.getProperty("mail.send.attachment.one.name"), new File(environment.getProperty("mail.send.attachment.one.location")));
    mailSender.send(mimeMessage);
    log.info("发送带有HTML文本的邮件成功");
}

During the test, you can directly get a string of HTML, sent over, it will display the contents of a normal HTML.

Send e-mail rendering thymeleaf

When some enterprise-level e-mail sent out, rendering the relevant specified template, there will be this summary. To thymeleaf example.

1, the introduction of the dependent thymeleaf

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

2, the configuration parameters thymeleaf

#指定模板文件的名称
mail.template.file.name=mailTempOne
##thymeleaf的配置
spring.thymeleaf.enabled=true
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
#指定模板文件的文件夹地址
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.check-template-location=true
spring.thymeleaf.check-template=false
spring.thymeleaf.cache=false

3, a simple template

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
    <p style="font-size: larger; color: burlywood">这是我发送出来的模板邮件,以下是邮件内容:</p><br/>
    内容:<span th:text="${content}"></span><br/>
    收件人:<span th:text="${mailTos}"></span><br/>
</body>
</html>

4, rendering the template code

/**
 * 渲染HTML模板
 * @param templateFile 具体的模板文件
 * @param paramMap 需要填充的参数
 */
public String renderTemplate(final String templateFile,Map<String,Object> paramMap){
    Context context=new Context(LocaleContextHolder.getLocale());
    context.setVariables(paramMap);
    return templateEngine.process(templateFile,context);
}

5, controller of the file directly after filling, and then to send e-mail service

@RequestMapping(value=prefix+"/send/template",method=RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public BaseResponse sendTemplateMail(@RequestBody @Validated MailRequest mailRequest, BindingResult bindingResult){
    BaseResponse response = new BaseResponse(StatusCode.Success);
    try {
        String checkResult = ValidatorUtils.checkResult(bindingResult);
        if (StringUtils.isNotBlank(checkResult)) {
            return new BaseResponse(StatusCode.Invalid_Params);
        }
        log.info("渲染HTML模板并发送带模板的邮件:{}",mailRequest);
        Map<String,Object> paramMap= Maps.newHashMap();
        paramMap.put("content",mailRequest.getContent());
        paramMap.put("mailTos",mailRequest.getMailTos());
        
        //获取渲染之后的HTML
        String html = mailService.renderTemplate(templateFileLocation,paramMap);

        String[] tos = StringUtils.split(mailRequest.getMailTos());
        //通过发送HTML的方式发送邮件
        mailService.sendHTMLMail(mailRequest.getSubject(),html,tos);
    } catch (Exception e) {
        response = new BaseResponse(StatusCode.Fail);
        log.error("发送HTML邮件异常,异常信息为:{}", e);
    }
    return response;
}

to sum up

Four kinds of sending mail operations, almost covering most application scenarios

1, sending simple text messages. 2, send messages with attachments. 3, send a message with HTML links. 4, send e-mail template rendering.

Published 133 original articles · won praise 37 · views 90000 +

Guess you like

Origin blog.csdn.net/liman65727/article/details/104348617