日常開發過程中,我們經常需要使用到郵件發送任務,比方說驗證碼的發送、日常信息的通知等。日常比較常用的郵件發送方包括:163、QQ等,本文主要講解Outlook SMTP的開啟方式、OutLook STARTTTL的配置、如何通過JavaMail來實現電子郵件的發送等。
Outlook作為微軟提供的企業電子郵件服務品牌,與其他品牌不同的是:Outlook使用的加密方式為STARTTTL。
一、開啟賬號的SMTP服務
使用個人郵箱的話,首先,通過office.com登錄你的微軟郵箱。進入設置頁面,點擊"同步電子郵件"選項,將POP選項選為"是",然后保存即可。
如果是商用類型帳號,子賬號是不具備開啟SMTP選項的權限的,需要聯系管理員開啟。
二、添加依賴
在pom.xml中添加Java Mail的依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>
三、添加配置
在yml文件中添加配置
spring:mail:username: ******@outlook.compassword: ****yourshost: smtp.office365.comport: 587properties:mail:default-encoding: UTF-8smtp:auth: truestarttls:enable: true
四、編寫Service
編寫service代碼,實現郵件發送功能
@Service
public class EmailServiceImpl implements EmailService {@Autowiredprivate JavaMailSender mailSender;@Value("${spring.mail.username}")private String username;@Overridepublic void sendSimpleEmail(String to, String subject, String content) {SimpleMailMessage message = new SimpleMailMessage();message.setTo(to);message.setSubject(subject);message.setText(content);message