Spring Boot 2.x 实践记:Mail

Posted mickjoust

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot 2.x 实践记:Mail相关的知识,希望对你有一定的参考价值。

目录

  1. Maven 依赖
  2. SMTP配置
  3. 发送简单邮件
  4. 发送带附件邮件
  5. 发送html格式邮件
  6. 实战
  7. 测试
  8. 小结

TL;DR

本文是实践如何在Spring Boot 2中使用JavaMailSender发送邮件:

  • 发送简单邮件
  • 发送带附件邮件
  • 发送HTML格式邮件

1. Maven 依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

2. SMTP配置

2.1. QQ邮箱

spring.mail.host=smtp.exmail.qq.com
spring.mail.username=xxx@xxx.com
spring.mail.password=xxxxxx

spring.mail.properties.mail.smtp.auth=true
# TLS , port 587
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

2.2. gmail

spring.mail.host=smtp.gmail.com
spring.mail.port=25
spring.mail.username=xxx@gmail.com
spring.mail.password=xxxxxx

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
 
# TLS , port 587
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

2.3. outlook

如果是内部服务器,需要由管理员提供基础信息。

spring.mail.host=smtp-mail.outlook.com
spring.mail.port=587
spring.mail.username=xxx@outlook.com
spring.mail.password=xxxxxx
 
spring.mail.properties.mail.protocol=smtp
spring.mail.properties.mail.tls=true
 
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.ssl.trust=smtp-mail.outlook.com

3. 发送简单邮件

@Resource
private JavaMailSender mailSender;

public void sendSimpleMail() 
    SimpleMailMessage message = new SimpleMailMessage();
  
    message.setFrom("xxx@xxx.com");
    message.setTo("xxx@xxx.com");
    message.setSubject("主题:简单邮件");
    message.setText("这是一封简单邮件");
    
    try 
        mailSender.send(message);
     catch (Exception e) 
        e.printStackTrace();
    

4. 发送带附件邮件

@Resource
private JavaMailSender mailSender;

public void sendAttachmentsMail() 
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    
    try 
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom("xxx@xxx.com");
        helper.setTo("xxx@xxx.com");
        helper.setSubject("主题:带有附件的邮件");
        helper.setText("有附件");
        FileSystemResource file = new FileSystemResource(new File("/data/test.xlsx"));
        helper.addAttachment("test.xlsx", file);
        
        mailSender.send(mimeMessage);
     catch (Exception e) 
        e.printStackTrace();
    

5. 发送HTML格式邮件

@Resource
private JavaMailSender mailSender;

public Boolean sendHtmlMail() 
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    try 
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom("xxx@xxx.com");
        helper.setTo("xxx@xxx.com");
        helper.setSubject("主题:带有html的邮件");
        helper.setText("<html><body><img src=\\"cid:test\\" ></body></html>", true);
        FileSystemResource file = new FileSystemResource(new File("/web/test.jpg"));
        helper.addInline("test.jpg", file);
    
        mailSender.send(mimeMessage);
     catch (Exception e) 
        e.printStackTrace();
    

6. 实战

  • github实战代码地址:

在实际邮件发送中,发送者通常为1个,而接受者通常是多个,而且还有抄送或密送,下面我们就来基于上面邮件发送的基本实现,来扩展实战一下。

6.1. 创建Spring Boot 启动类

package com.mickjoust.demo.springboot2_in_action.mail;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author mickjoust
 **/
@SpringBootApplication
public class AppStartMail 
    public static void main(String[] args) 
        SpringApplication.run(AppStartMail.class,args);
    


6.2. 创建邮件对象

为了方便模拟传参数,我们创建一个简单的邮件对象。

package com.mickjoust.demo.springboot2_in_action.mail;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


/**
 * @author mickjoust
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MailInfo 

    private String subject;
    private String content;
    private String from;
    private String[] to;
    private String[] cc;
    private String[] bcc;
    private String fileName;
    private String filePath;

6.3. 创建Restful API

分别提供三个接口,接受发送邮件,如果发送成功则返回成功,否则返回失败。

package com.mickjoust.demo.springboot2_in_action.mail;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;

/**
 * @author mickjoust
 **/
@Slf4j
@RestController
public class TestSendMailController 

    @Resource
    private SendMailService sendMailService;


    @PostMapping("/mail/simple")
    public String sendSimpleMail(@RequestBody MailInfo mailInfo)
        if (sendMailService.sendSimpleMail(mailInfo)) 
            return "true";
        
        return "false";
    

    @PostMapping("/mail/attachment")
    public String sendAttachmentsMail(@RequestBody MailInfo mailInfo)
        if (sendMailService.sendAttachmentsMail(mailInfo)) 
            return "true";
        
        return "false";
    

    @PostMapping("/mail/html")
    public String sendHtmlMail(@RequestBody MailInfo mailInfo)
        if (sendMailService.sendHtmlMail(mailInfo)) 
            return "true";
        
        return "false";
    



6.4. 实现邮件发送服务

package com.mickjoust.demo.springboot2_in_action.mail;


/**
 * @author mickjoust
 **/
public interface SendMailService 

    Boolean sendSimpleMail(MailInfo mailInfo);

    Boolean sendAttachmentsMail(MailInfo mailInfo);

    Boolean sendHtmlMail(MailInfo mailInfo);

package com.mickjoust.demo.springboot2_in_action.mail;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

/**
 * @author mickjoust
 **/
@Slf4j
@Service("sendMailService")
public class SendMailServiceImpl implements SendMailService 

    @Resource
    private JavaMailSender mailSender;

    private boolean isEmpty(final String[] array) 
        return array == null || array.length == 0;
    

    private boolean isNotEmpty(final String[] array) 
        return !isEmpty(array);
    

    /**
     * 发送普通邮件
     * @param subject 主题
     * @param content 内容
     * @param from 发自
     * @param to 发送
     * @param cc 抄送
     * @param bcc 密送
     * @return 返回
     */
    public Boolean sendSimpleMail(String subject, String content, String from, String[] to,String[] cc,String[] bcc) 

        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(from);
        message.setTo(to);
        if (isNotEmpty(cc))
            message.setCc(cc);
        
        if (isNotEmpty(bcc))
            message.setBcc(bcc);
        
        message.setSubject(subject);
        message.setText(content);

        try 
            mailSender.send(message);
            return true;
         catch (Exception e) 
            log.error("===发送邮件异常",e);
        
        return false;
    

    /**
     * 发送附件邮件
     * @param subject
     * @param content
     * @param from
     * @param fillepath /web/test.xlsx
     * @param filename test.xlsx
     * @param to
     * @param cc
     * @param bcc
     * @return
     */
    public Boolean sendAttachmentsMail(String subject,String content,String from, String fillepath, String filename,
                                       String[] to,
                                       String[] cc,
                                       String[] bcc) 
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try 
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            if (isNotEmpty(cc)) 
                helper.setCc(cc);
            
            if (isNotEmpty(bcc))
                helper.setBcc(bcc);
            
            helper.setSubject(subject);
            helper.setText(content);
            FileSystemResource file = new FileSystemResource(new File(fillepath));
            helper.addAttachment(filename, file);
         catch (Exception e) 
            e.printStackTrace();
            log.error("===创建附件邮件异常", e);
        
        try 
            mailSender.send(mimeMessage);
            return true;
         catch (Exception e) 
            log.error("===发送邮件异常",e);
        
        return false;
    

    /**
     * 发送富文本邮件
     * @param subject
     * @param content 比如:<html><body><img src=\\"cid:test\\" ></body></html>
     * @param from
     * @param fillepath 比如:/web/test.jpg
     * @param filename 比如,test
     * @param to
     * @param cc
     * @param bcc
     * @return
     */
    public Boolean sendHtmlMail(String subject,String content,String from, String fillepath, String filename,
                                String[] to,
                                String[] cc,
                                String[] bcc) 

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try 
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            if (isNotEmpty(cc)) 
                helper.setCc(cc);
            
            if (isNotEmpty(bcc))
                helper.setBcc(bcc);
            
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(fillepath));
            helper.addInline(filename, file);
         catch (Exception e) 
            log.error("===创建富文本邮件异常", e);
        
        try 
            mailSender.send(mimeMessage);
            return true;
         catch (Exception e) 
            log.error("===发送邮件异常",e);
        
        return false;
    


    @Override
    public Boolean sendSimpleMail(MailInfo mailInfo) 
        return sendSimpleMail(mailInfo.getSubject(),mailInfo.getContent(),mailInfo.getFrom(),
                mailInfo.getTo(),mailInfo.getCc(),mailInfo.getBcc());
    

    @Override
    public Boolean sendAttachmentsMail(MailInfo mailInfo) 
        return sendAttachmentsMail(mailInfo.getSubject(),mailInfo.getContent(),mailInfo.getFrom(),
                mailInfo.getFilePath(),mailInfo.getFileName(),mailInfo.getTo(),mailInfo.getCc(),mailInfo.getBcc());
    

    @Override
    public Boolean sendHtmlMail(MailInfo mailInfo) 
        return sendHtmlMail(mailInfo.getSubject(),mailInfo.getContent(),mailInfo.getFrom(),
                mailInfo.getFilePath(),mailInfo.getFileName(),mailInfo.getTo(),mailInfo.getCc(),mailInfo.getBcc());
    

7. 测试

8. 小结

到此,我们就学会了在Spring Boot 2 中发送邮件的方法。

以上是关于Spring Boot 2.x 实践记:Mail的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 2.x 实践记:Mail

(汇总)Spring Boot 实践折腾记 & Spring Boot 2.x 实践记

Spring Boot 2.x 实践记:Gson

Spring Boot 2.x 实践记:@SpringBootTest

Spring Boot 2.x 实践记:@SpringBootTest

Spring Boot 2.x 实践记:@SpringBootTest