SpringBoot整合邮件

  • 邮箱设置
    开启IMAP/SMTP服务,然后增加授权码,所有邮箱都如此
    在这里插入图片描述
  • 在pom文件中添加如下,导入jar包
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  • 在application.properties添加,邮箱参数配置

#发送邮件设置
spring.mail.host=smtp.163.com 或者smtp.qq.com
#发件人邮件地址
spring.mail.username=邮箱名称@163.com  /qq邮箱
#QQ邮箱授权码
spring.mail.password=授权码
spring.mail.protocol=smtps
spring.mail.default-encoding=utf-8
spring.mail.properties.mail.smtp.ssl.enable=true
  • 编写 工具类
@Component
public class MailClient {

    private static final Logger logger= LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送纯文本的简单邮件
     * @param to
     * @param subject
     * @param content
     */
    public void sendSimpleMail(String to,String subject,String content){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            logger.info("邮件发送成功");
        }catch (Exception e){
            logger.error("发送邮件失败"+e.getMessage());
        }

    }

    /**
     * 发送html格式的文件
     * @param to
     * @param subject
     * @param content
     */
    public void sendMail(String to,String subject,String content){
        try {

            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);


            mailSender.send(helper.getMimeMessage());
            logger.info("邮件已经发送。");
        }catch (MessagingException e){
            logger.error("发送邮件失败"+e.getMessage());
        }
    }

    /**
     * 发送带附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    public  void sendAttachmentsMail(String to,String subject,String content,String   filePath){
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            //true表示创建一个multipart message

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file=new FileSystemResource(new File(filePath));
            String filename = filePath.substring(filePath.lastIndexOf(File.separator));

            helper.addAttachment(filename,file);
            mailSender.send(mimeMessage);
            logger.info("邮件已经发送。");

        }catch (MessagingException e){
            logger.error("发送邮件失败"+e.getMessage());
        }

    }

    /**
     * 
|发送嵌入静态资源(一般是图片)的邮件|  |
|------------------|--|
|                  |  |

     * @param to
     * @param subject
     * @param content
     * @param rscPath  静态资源路径和文件名
     * @param rscId   静态资源id
     */
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            //true表示创建一个multipart message

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);
            mailSender.send(mimeMessage);
            logger.info("邮件已经发送。");

        }catch (MessagingException e){
            logger.error("发送邮件失败"+e.getMessage());
        }
    }
}
  • 测试类

@RestController
public class EmailController {
    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;
    /*这里要导入包
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
*/

    private static final String to="要发送的邮箱";

    @GetMapping("/to")
    public void sendSimpleMail(){
        mailClient.sendSimpleMail(to,"测试","123456");
    }

    @GetMapping("/to1")
    public void sendHtmlMail(){
        //使用模板thymeleaf
        //Context是导这个包import org.thymeleaf.context.Context;
        Context context = new Context();
        context.setVariable("username","test");
        ///mail/demo 是发送的模板,文件如下
        String content = templateEngine.process("/mail/demo", context);
        mailClient.sendMail(to, "主题:html邮件", content);
//这里的content也可以直接写成 <p>欢迎你,<span> username</span>!</p>;
    }

    @GetMapping("/to2")
    public void sendAttachmentsMail(){
        mailClient.sendAttachmentsMail(to,"主题:带附件的邮箱","test","C:\\Users\\lf\\Desktop\\新建文件夹\\1png.png");
    }

    @GetMapping("/to3")
    public void sendInlineResourceMail() {
        String rscId = "test";
        mailClient.sendInlineResourceMail(to,
                "主题:嵌入静态资源的邮件",
                "<html><body>这是有嵌入静态资源:<img src=\'cid:" + rscId + "\' ></body></html>",
                "D:\\1.jpg",
                rscId);
    }
}

/mail/demo放在template文件下面,内容如下

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>邮件示例</title>
</head>
<body>
<p>欢迎你, <span style="color:red;" th:text="${username}"></span>!</p>
</body>
</html>
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页