最近項目用到郵件系統,開始了解javaMail。。。話不多說先上代碼:
pom依賴:
<!-- 郵件 https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
工具類:
import java.util.Date;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailUtils {
//發件人地址
private static String senderAddress = "1234567891@163.com";
//收件人地址
private static String recipientAddress = "123456789@qq.com";
//發件人賬戶
public static String senderAccount = "1234567891@163.com";
//發件人授權碼
public static String auth = "xxxxxxx";
//郵件主題
public static String subject = "xxxxxx通知";
//郵件正文
public static String content = "您有一則xxxxx!";
public static void main(String [] args) throws MessagingException {
//1.連接郵件服務器的配置參數
Properties properties = new Properties();
//設置用戶認證方式
properties.setProperty("mail.smtp.auth", "true");
//設置傳輸協議
properties.setProperty("mail.transport.protocol", "smtp");
//設置發件人的SMTP服務器地址
properties.setProperty("mail.smtp.host", "smtp.163.com");
//properties.setProperty("mail.smtp.port", "465");
//2.創建定義整個應用程序所需的環境信息的Session對象
Session session = Session.getInstance(properties);
session.setDebug(true);
//3.創建郵件的實例對象
MimeMessage msg = getMimeMessage(session);
//4.根據session對象獲取郵件傳輸對象
Transport transport = session.getTransport("smtp");
transport.connect("smtp.163.com", senderAccount, auth);
//發送郵件,並發送到所有收件人地址,message.getAllRecipients()獲取到創建又見對象時添加的所有收件人抄送人密送人
transport.sendMessage(msg, msg.getAllRecipients());
//如果只想發送給指定的人,可以如下寫法
//transport.sendMessage(msg, new Address[]{new InternetAddress("xxx@qq.com")});
//5.關閉郵件鏈接
transport.close();
}
/**
* 獲得創建一封郵件的實例對象
* @param session
* @return
* @throws MessagingException
* @throws AddressException
*/
public static MimeMessage getMimeMessage(Session session) throws MessagingException {
//創建郵件的實例對象
MimeMessage msg = new MimeMessage(session);
//設置發件人地址
msg.setFrom(new InternetAddress(senderAddress));
/*
* 設置收件人地址(可以增加多個收件人,抄送人,密送)
* MimeMessage.RecipientType.TO 發送
* MimeMessage.RecipientType.CC 抄送
* MimeMessage.RecipientType.BCC 密送
*/
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipientAddress));
//設置郵件主題
msg.setSubject(subject, "UTF-8");
//設置郵件正文
msg.setContent(content, "text/html;charset=UTF-8");
//設置郵件的發送時間默認立即發送
msg.setSentDate(new Date());
return msg;
}
}
需要注意首先發件人郵箱需要設置開啟POP3/SMTP/IMAP協議
transport.connect("smtp.163.com", senderAccount, auth);這里的參數注意第三個不是密碼