Spring Boot發送郵件


如何使用Spring Boot發送郵件?

Spring Boot為發送郵件提供了starter:spring-boot-starter-mail 。

接下來,我們看看如何用Spring Boot發送郵件。

 

一、配置郵箱

這里我們使用163網易郵箱

1.開啟SMTP服務

 2.設置/重置客戶端授權密碼

 

二、編碼實現

1.添加依賴

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

2.編寫配置

1 # mail
2 spring.mail.host=smtp.163.com
3 spring.mail.username=xxxxxx@163.com
4 spring.mail.password=xxxxxx
5 spring.mail.from=xxxxxx@163.com
6 spring.mail.properties.mail.smtp.auth=true
7 spring.mail.properties.mail.smtp.starttls.enable=true
8 spring.mail.properties.mail.smtp.starttls.required=true

3.編寫郵件發送實體類

 1 package com.alanlee.dto;
 2 
 3 import lombok.AllArgsConstructor;
 4 import lombok.Getter;
 5 import lombok.NoArgsConstructor;
 6 import lombok.Setter;
 7 
 8 import javax.validation.constraints.NotBlank;
 9 import javax.validation.constraints.Pattern;
10 
11 @Getter
12 @Setter
13 @NoArgsConstructor
14 @AllArgsConstructor
15 public class Mail {
16 
17     @Pattern(regexp = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$", message = "郵箱格式不正確")
18     private String to;
19 
20     @NotBlank(message = "標題不能為空")
21     private String title;
22 
23     @NotBlank(message = "正文不能為空")
24     private String content;
25 
26     private String msgId;// 消息id
27 
28 }

4.編寫郵件發送工具類

 1 package com.alanlee.util;
 2 
 3 import com.alanlee.dto.Mail;
 4 import lombok.extern.slf4j.Slf4j;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.beans.factory.annotation.Value;
 7 import org.springframework.core.io.FileSystemResource;
 8 import org.springframework.mail.MailException;
 9 import org.springframework.mail.SimpleMailMessage;
10 import org.springframework.mail.javamail.JavaMailSender;
11 import org.springframework.mail.javamail.MimeMessageHelper;
12 import org.springframework.stereotype.Component;
13 
14 import javax.mail.internet.MimeMessage;
15 import java.io.File;
16 
17 /**
18  * 郵件發送工具類
19  *
20  * @author AlanLee
21  */
22 @Component
23 @Slf4j
24 public class MailUtil {
25 
26     /**
27      * 發件人
28      */
29     @Value("${spring.mail.from}")
30     private String from;
31 
32     @Autowired
33     private JavaMailSender mailSender;
34 
35     /**
36      * 發送簡單郵件
37      *
38      * @param mail
39      */
40     public boolean send(Mail mail) {
41         String to = mail.getTo();// 目標郵箱
42         String title = mail.getTitle();// 郵件標題
43         String content = mail.getContent();// 郵件正文
44 
45         SimpleMailMessage message = new SimpleMailMessage();
46         message.setFrom(from);
47         message.setTo(to);
48         message.setSubject(title);
49         message.setText(content);
50 
51         try {
52             mailSender.send(message);
53             log.info("郵件發送成功");
54             return true;
55         } catch (MailException e) {
56             log.error("郵件發送失敗, to: {}, title: {}", to, title, e);
57             return false;
58         }
59     }
60 
61     /**
62      * 發送附件郵件(暫無調用,后續完善業務邏輯)
63      *
64      * @param mail 郵件
65      * @param file 附件
66      */
67     public boolean sendAttachment(Mail mail, File file) {
68         String to = mail.getTo();
69         String title = mail.getTitle();
70         String content = mail.getContent();
71 
72         MimeMessage message = mailSender.createMimeMessage();
73         try {
74             MimeMessageHelper helper = new MimeMessageHelper(message, true);
75             helper.setFrom(from);
76             helper.setTo(to);
77             helper.setSubject(title);
78             helper.setText(content);
79             FileSystemResource resource = new FileSystemResource(file);
80             String fileName = file.getName();
81             helper.addAttachment(fileName, resource);
82             mailSender.send(message);
83             log.info("附件郵件發送成功");
84             return true;
85         } catch (Exception e) {
86             log.error("附件郵件發送失敗, to: {}, title: {}", to, title, e);
87             return false;
88         }
89     }
90 
91 }

5.最后自己寫個main方法之類的,調用測試能否發送成功吧,自己動手才是王道。

 

結束語:在最平凡的生活里謙卑和努力,總有一天你會站在最亮的地方,活成自己曾經渴望的模樣。

 

佛系博主:AlanLee

博客地址:http://www.cnblogs.com/AlanLee

GitHub地址:https://github.com/AlanLee-Java

本文出自博客園,歡迎大家加入博客園。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM