zoukankan      html  css  js  c++  java
  • Spring Boot简单实现发送邮件功能

    我们先看发送邮件所需要的依赖

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

    然后是邮件服务器的配置

    spring.mail.host=smtp.163.com
    spring.mail.username=*********@163.com
    spring.mail.password=********      //授权码
    spring.mail.default-encoding=utf-8
    
    mail.fromMail.addr=******

    在这里我使用的是163免费邮箱,各类邮箱服务器地址请参考 https://blog.csdn.net/lingduo24/article/details/81137773

    在密码这里我遇到了一个坑,就是你需要去开启授权并设置授权码,最后使用授权码来登陆连接

    至此,准备工作已经完成,接下来看发送邮件的方法类

    @Component
    @Slf4j
    public class MailService {
    
        @Autowired
        private JavaMailSender mailSender;
    
        @Value("${mail.fromMail.addr}")
        private String from;

    第一种是发送最简单的邮件,即一段文本,方法如下

    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);
                log.error("简单邮件已经发送。");
            } catch (Exception e) {
                log.error("发送简单邮件时发生异常!",e);
            }
        }

    测试方法如下

     1 @RunWith(SpringRunner.class)
     2 @SpringBootTest
     3 public class MailServiceTest {
     4 
     5     @Autowired
     6     private MailService mailService;
     7 
     8     @Autowired
     9     private TemplateEngine templateEngine;
    10 
    11     @Test
    12     public void sendSimpleMail() {
    13         mailService.sendSimpleMail("**********@qq.com","test simple mail","hello this is simple mail");
    14     }

    第二种是发送一段HTML格式的邮件,方法如下

     1 public void sendHtmlMail(String to, String subject, String content) {
     2         MimeMessage message = mailSender.createMimeMessage();
     3 
     4         try {
     5             MimeMessageHelper helper = new MimeMessageHelper(message, true);
     6             helper.setFrom(from);
     7             helper.setTo(to);
     8             helper.setSubject(subject);
     9             helper.setText(content, true);
    10 
    11             mailSender.send(message);
    12             log.error("HTML邮件已经发送。");
    13         } catch (Exception e) {
    14             log.error("发送HTML邮件时发生异常!",e);
    15         }
    16     }

    测试方法如下

    1 @Test
    2     public void sendHtmlMail() {
    3         String content = "<html>
    " +
    4                             "<body>
    " +
    5                                 "<h3>Hello World!这是一封HTML邮件!</h3>
    " +
    6                             "</body>
    " +
    7                          "</html>";
    8         mailService.sendHtmlMail("************","test html mail",content);
    9     }

    第三种是发送模板邮件,在这里我以thymeleaf为模板,我们首先添加thymeleaf的依赖

    1 <dependency>
    2             <groupId>org.springframework.boot</groupId>
    3             <artifactId>spring-boot-starter-thymeleaf</artifactId>
    4 </dependency>

    然后在resources emplates路径下添加HTML文件EmailTemplate.html

     1 <!DOCTYPE html>
     2 <html lang="zh" xmlns:th="http://www.thymeleaf.org">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Title</title>
     6 </head>
     7 <body>
     8     尊敬的<span th:text="${name}"/> 9     您好,这是一封模板邮件,
    10 </body>
    11 </html>

    发送模板邮件时我们使用的依然是发送HTML的方法,只是对HTML进行了处理,测试方法如下

    @Test
        public void sendTemplateMail() {
            Context context = new Context();
            context.setVariable("name","******");
            String emailContent = templateEngine.process("EmailTemplate",context);
            mailService.sendHtmlMail("************","test template mail",emailContent);
        }

    第四种是发送带附件的邮件,方法如下

     1 public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
     2         MimeMessage message = mailSender.createMimeMessage();
     3 
     4         try {
     5 
     6             MimeMessageHelper helper = new MimeMessageHelper(message,true);
     7             helper.setFrom(from);
     8             helper.setTo(to);
     9             //helper.setCc();
    10             //helper.setBcc();
    11             helper.setSubject(subject);
    12             helper.setText(content,true);
    13 
    14             FileSystemResource file = new FileSystemResource(new File(filePath));
    15             String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
    16             helper.addAttachment(fileName,file);
    17 
    18             mailSender.send(message);
    19             log.error("带附件邮件已经发送。");
    20         } catch (MessagingException e) {
    21             log.error("带附件邮件发送发生异常!",e);
    22         }
    23     }

    当有多个附件时,我们可以多次使用addAttachment方法,测试方法如下

    @Test
        public void sendAttachmentsMail() {
            String filePath = "*****************";
            mailService.sendAttachmentsMail("*************@qq.com","test attachment email","有附件,请注意查收!",filePath);
        }

    以上就是简单使用Springboot发送邮件的四种方法,所有测试方法亲测无误

    欢迎指正交流!

  • 相关阅读:
    POJ 1426 Find The Multiple(数论——中国同余定理)
    POJ 2253 Frogger(Dijkstra变形——最短路径最大权值)
    POJ 3790 最短路径问题(Dijkstra变形——最短路径双重最小权值)
    POJ 3278 Catch That Cow(模板——BFS)
    HDU 1071 The area
    HDU 1213 How Many Tables(模板——并查集)
    POJ 1611 The Suspects
    light oj 1214 Large Division
    POJ 1258 Agri-Net(Prim算法求解MST)
    POJ 2387 Til the Cows Come Home(模板——Dijkstra算法)
  • 原文地址:https://www.cnblogs.com/JINJAY/p/10817964.html
Copyright © 2011-2022 走看看