1. 程式人生 > >Spring JavaMailSender傳送郵件

Spring JavaMailSender傳送郵件

個人選擇的傳送服務伺服器是QQ,所以要進行開啟QQ郵箱的SMTP服務,過程如圖所示:

在賬戶下設定開啟SMTP服務,需記住顯示的STMP密碼,點選“開啟”後發簡訊過去即可開啟

EmailSendTest:
import org.junit.Test;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

public class MailSendTest {
    	@Test
   	public void springEmailSender() throws IOException {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        //伺服器SMTP域,可百度自行搜尋對應域
        mailSender.setHost("smtp.qq.com");
        mailSender.setDefaultEncoding("UTF-8");
        //傳送方服務郵箱
        mailSender.setUsername("你的賬號@qq.com");
        //傳送方SMTP密碼(並非你的QQ密碼)
        mailSender.setPassword("16位的SMTP密碼");
        Properties props = new Properties();
        //載入根目錄下的mail.properties檔案
        props.load(ClassLoader.getSystemResourceAsStream("mail.properties"));
        //設定email會話
        mailSender.setSession(Session.getInstance(props));

        //新建郵件
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //收件人郵箱
        mailMessage.setTo("接收方郵箱@163.com");
        //郵件標題
        mailMessage.setSubject("測試郵件");
        //郵件傳送方郵箱,若與username值相同將丟擲from與username不符的異常
        mailMessage.setFrom("傳送方郵箱@qq.com");
        //郵件內容
        mailMessage.setText("a test email");

        //進行郵件傳送
        mailSender.send(mailMessage);
    }
}


 根目錄下的資原始檔mail.properties:
  

#若不設定將丟擲iis security異常
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.port=465


個人成功測試圖如下: