SpringBoot 发送邮件

avatar 2018年02月06日23:10:15 7 2807 views
博主分享免费Java教学视频,B站账号:Java刘哥
SpringBoot 用了一段时间了,无需复杂的配置真的是用得很爽。在做登录,注册,找回密码模块中必然要用到邮箱,本文介绍 SpringBoot 发送邮件。 这里,博主使用腾讯企业邮箱(master@liuyanzhao.com) 给个人邮箱发送邮件。 目前也测试了 126 邮箱,163 邮箱,qq 邮箱,新浪邮箱。 至少 腾讯企业邮箱,163 邮箱,qq 邮箱测试成功;126 邮箱由于自己 ip 好像被封了一直不成功,新浪邮箱是安全问题,授权失败。    

一、Maven

  1. <!--邮件-->
  2. <dependency>
  3.     <groupId>org.springframework.boot</groupId>
  4.     <artifactId>spring-boot-starter-mail</artifactId>
  5. </dependency>
 

二、application.properties

  1. #mail
  2. #qq企业邮箱
  3. #spring.mail.host=smtp.exmail.qq.com
  4. #spring.mail.username=master@liuyanzhao.com
  5. #spring.mail.password=登录密码
  6. #163邮箱
  7. #spring.mail.host=smtp.163.com
  8. #spring.mail.username=liuyanzhao_com@163.com
  9. #spring.mail.password=授权码
  10. #qq邮箱
  11. spring.mail.host=smtp.qq.com
  12. spring.mail.username=847064370@qq.com
  13. spring.mail.password=授权码
  14. spring.mail.properties.smtp.auth=true
  15. spring.mail.properties.smtp.starttls.enable=true
  16. spring.mail.properties.smtp.starttls.required=true
  17. spring.mail.properties.mail.smtp.ssl.enable=true
  这里补充一下,
邮箱 host username password
QQ邮箱 smtp.qq.com 如 847064370@qq.com  授权码(不是qq密码和邮箱独立密码)
126邮箱 smtp.126.com 如 example@126.com 授权码(不是登录密码)
163邮箱 smtp.163.com 如 example@163.com 授权码(不是登录密码)
新浪邮箱 smtp.sina.com 如 example@sina.com 登录密码
阿里云邮箱 smtp.aliyun.com 如 example@aliyun.com 登录密码
   

三、MailService

  1. package com.liuyanzhao.chuyun.service;
  2. import ch.qos.logback.classic.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.core.io.FileSystemResource;
  7. import org.springframework.mail.SimpleMailMessage;
  8. import org.springframework.mail.javamail.JavaMailSender;
  9. import org.springframework.mail.javamail.MimeMessageHelper;
  10. import org.springframework.stereotype.Service;
  11. import javax.mail.MessagingException;
  12. import javax.mail.internet.MimeMessage;
  13. import java.io.File;
  14. /**
  15.  * @author 言曌
  16.  * @date 2018/2/6 下午8:25
  17.  */
  18. @Service
  19. public class MailService {
  20.     private final Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());
  21.     @Autowired
  22.     private JavaMailSender sender;
  23.     @Value("${spring.mail.username}")
  24.     private String from;
  25.     /**
  26.      * 发送纯文本的简单邮件
  27.      * @param to
  28.      * @param subject
  29.      * @param content
  30.      */
  31.     public void sendSimpleMail(String to, String subject, String content){
  32.         SimpleMailMessage message = new SimpleMailMessage();
  33.         message.setFrom(from);
  34.         message.setTo(to);
  35.         message.setSubject(subject);
  36.         message.setText(content);
  37.         try {
  38.             sender.send(message);
  39.             logger.info("简单邮件已经发送。");
  40.         } catch (Exception e) {
  41.             logger.error("发送简单邮件时发生异常!", e);
  42.         }
  43.     }
  44.     /**
  45.      * 发送html格式的邮件
  46.      * @param to
  47.      * @param subject
  48.      * @param content
  49.      */
  50.     public void sendHtmlMail(String to, String subject, String content){
  51.         MimeMessage message = sender.createMimeMessage();
  52.         try {
  53.             //true表示需要创建一个multipart message
  54.             MimeMessageHelper helper = new MimeMessageHelper(message, true);
  55.             helper.setFrom(from);
  56.             helper.setTo(to);
  57.             helper.setSubject(subject);
  58.             helper.setText(content, true);
  59.             sender.send(message);
  60.             logger.info("html邮件已经发送。");
  61.         } catch (MessagingException e) {
  62.             logger.error("发送html邮件时发生异常!", e);
  63.         }
  64.     }
  65.     /**
  66.      * 发送带附件的邮件
  67.      * @param to
  68.      * @param subject
  69.      * @param content
  70.      * @param filePath
  71.      */
  72.     public void sendAttachmentsMail(String to, String subject, String content, String filePath){
  73.         MimeMessage message = sender.createMimeMessage();
  74.         try {
  75.             //true表示需要创建一个multipart message
  76.             MimeMessageHelper helper = new MimeMessageHelper(message, true);
  77.             helper.setFrom(from);
  78.             helper.setTo(to);
  79.             helper.setSubject(subject);
  80.             helper.setText(content, true);
  81.             FileSystemResource file = new FileSystemResource(new File(filePath));
  82.             String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
  83.             helper.addAttachment(fileName, file);
  84.             sender.send(message);
  85.             logger.info("带附件的邮件已经发送。");
  86.         } catch (MessagingException e) {
  87.             logger.error("发送带附件的邮件时发生异常!", e);
  88.         }
  89.     }
  90.     /**
  91.      * 发送嵌入静态资源(一般是图片)的邮件
  92.      * @param to
  93.      * @param subject
  94.      * @param content 邮件内容,需要包括一个静态资源的id,比如:<img src=\"cid:rscId01\" >
  95.      * @param rscPath 静态资源路径和文件名
  96.      * @param rscId 静态资源id
  97.      */
  98.     public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
  99.         MimeMessage message = sender.createMimeMessage();
  100.         try {
  101.             //true表示需要创建一个multipart message
  102.             MimeMessageHelper helper = new MimeMessageHelper(message, true);
  103.             helper.setFrom(from);
  104.             helper.setTo(to);
  105.             helper.setSubject(subject);
  106.             helper.setText(content, true);
  107.             FileSystemResource res = new FileSystemResource(new File(rscPath));
  108.             helper.addInline(rscId, res);
  109.             sender.send(message);
  110.             logger.info("嵌入静态资源的邮件已经发送。");
  111.         } catch (MessagingException e) {
  112.             logger.error("发送嵌入静态资源的邮件时发生异常!", e);
  113.         }
  114.     }
  115. }
 

四、测试类

  1. package com.liuyanzhao.chuyun.service;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.test.context.junit4.SpringRunner;
  7. import java.util.Date;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. /**
  11.  * @author 言曌
  12.  * @date 2018/2/6 下午8:28
  13.  */
  14. @SpringBootTest
  15. @RunWith(SpringRunner.class)
  16. public class MailServiceTest{
  17.     @Autowired
  18.     private MailService mailService;
  19.     private String toEmailAddress = "847064370@qq.com";
  20.     @Test
  21.     public void sendSimpleMail() throws Exception {
  22.         mailService.sendSimpleMail(toEmailAddress, "主题:简单邮件""测试邮件内容");
  23.     }
  24.     @Test
  25.     public void sendHtmlMail() throws Exception {
  26.         Map<String, Object> model = new HashMap<String, Object>();
  27.         model.put("time"new Date());
  28.         model.put("message""这是测试的内容。。。");
  29.         model.put("toUserName""刘言曌");
  30.         model.put("fromUserName""言曌博客管理员");
  31.         String content = "<h1>Hello,言曌!</h1>";
  32.         mailService.sendHtmlMail(toEmailAddress, "主题:html邮件", content);
  33.     }
  34.     @Test
  35.     public void sendAttachmentsMail() throws Exception {
  36.         mailService.sendAttachmentsMail(toEmailAddress, "主题:带附件的邮件""有附件,请查收!""/Users/liuyanzhao/Documents/刘言曌.xlsx");
  37.     }
  38.     @Test
  39.     public void sendInlineResourceMail() throws Exception {
  40.         String rscId = "rscId001";
  41.         mailService.sendInlineResourceMail(toEmailAddress,
  42.                 "主题:嵌入静态资源的邮件",
  43.                 "<html><body>这是有嵌入静态资源:<img src='cid:" + rscId + "\' width='128px' height='128px' ></body></html>",
  44.                 "/Users/liuyanzhao/Pictures/avatar.jpg",
  45.                 rscId);
  46.     }
  47. }
   

五、效果图

使用腾讯企业邮箱(密码是登录密码)   简单邮件   HTML邮件   附件邮件   资源邮件     本文地址:https://liuyanzhao.com/7484.html
  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:1   待审核评论数:0
  1. avatar 热心网友

    看了5、6篇博客,到博主这才解决了问题,赞!