項目地址:https://github.com/zhaopeng01/springboot-study/tree/master/study6
在SpringBoot中發送郵件
1.依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.工具類
package com.zyc.utils;
import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendMail {
private static Logger log = LoggerFactory.getLogger(SendMail.class);
public static final String SENDER = "[email protected]";
public static boolean send(String addressee, String subject, String text) {
try {
//用於讀取配置文件
Properties props = new Properties();
//開啓Debug調試
props.setProperty("mail.debug", "true");
//發送服務器需要身份驗證
props.setProperty("mail.smtp.auth", "true");
//發送郵件服務器的主機名
props.setProperty("mail.host", "smtp.qq.com");
//發送郵件協議
props.setProperty("mail.transport.protocol", "smtp");
//開啓ssl加密(並不是所有的郵箱服務器都需要,但是qq郵箱服務器是必須的)
MailSSLSocketFactory msf = new MailSSLSocketFactory();
msf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", msf);
//獲取Session會話實例(javamail Session與HttpSession的區別是Javamail的Session只是配置信息的集合)
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//用戶名密碼驗證(取得的授權嗎)
return new PasswordAuthentication(SENDER, "這裏填的是授權碼");
}
});
//抽象類MimeMessage爲實現類 消息載體封裝了郵件的所有消息
Message message = new MimeMessage(session);
//設置郵件主題
message.setSubject(subject);
//封裝需要發送電子郵件的信息
message.setText(text);
//設置發件人地址
message.setFrom(new InternetAddress(SENDER));
//此類的功能是發送郵件 又會話獲得實例
Transport transport = session.getTransport();
//開啓連接
transport.connect();
//設置收件人地址郵件信息
transport.sendMessage(message, new Address[]{new InternetAddress(addressee)});
//郵件發送後關閉信息
transport.close();
} catch (Exception e) {
log.info("郵件發送異常");
return false;
}
return true;
}
}
3.controller
package com.zyc.controller;
import com.zyc.utils.SendMail;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description:發送郵件
* @author zhaopeng
* @email [email protected]
*/
@RestController
@RequestMapping("/mail")
public class MailController {
@GetMapping("/send")
public void send() {
SendMail.send("[email protected]", "這是主題", "這是內容");
}
}
然後就可以啓動項目,然後訪問http://localhost:8080/mail/send 就ok了就打開自己郵箱看看吧;
效果
好的到這裏本篇文章就先到此了,創作不易,如果那裏有不合適的地方還請大家多多指教,寫這篇博的目的主要就是爲了方便自己以後的一個回憶和朋友學習時的一個參考,希望爲大家可以帶來幫助 ~ ~&
虛心的去學習,自信的去工作~