這裡我們以QQ郵箱為例。 一、導入依賴: <dependencies> <!-- https://mvnrepository.com/artifact/javax.activation/activation --> <dependency> <groupId>javax.activation</gr ...
這裡我們以QQ郵箱為例。
一、導入依賴:
<dependencies> <!-- https://mvnrepository.com/artifact/javax.activation/activation --> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.mail/mail --> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> </dependencies>
二、設置自己的QQ郵箱
開啟以上兩項服務。
三、具體實現
import com.sun.mail.util.MailSSLSocketFactory; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class SendEmail { /* addressee:收件人郵箱 *title:郵件標題標題 *content:郵件內容 */ public static void send(String addressee, String title, String content) throws Exception { Properties prop = new Properties(); prop.setProperty("mail.host", "smtp.qq.com");//郵件伺服器:QQ prop.setProperty("mail.transport.protocol", "smtp");//郵件發送協議:smtp prop.setProperty("mail.smtp.auth", "true");//需要驗證用戶名和密碼 //QQ郵箱,還需要設置SSL加密 MailSSLSocketFactory factory = new MailSSLSocketFactory(); factory.setTrustAllHosts(true); prop.put("maim.smtp.ssl.enable", "true"); prop.put("maim.smtp.ssl.socketFactory", factory); //javaMail發送email的五個步驟 //1.定義一個整個應用環境需要的session對象 Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("自己的郵箱", "授權碼"); } }); //開啟session的debug模式 session.setDebug(true); //2.通過session得到transport對象 Transport transport = session.getTransport(); //3.使用郵箱用戶名和授權碼連接上伺服器 transport.connect("smtp.qq.com", "自己的郵箱", 授權碼"); //4.創建郵件 //創建郵件對象 MimeMessage message = new MimeMessage(session); //發郵件人 message.setFrom(new InternetAddress("自己的郵箱")); //收件人 可以群發setRecipients message.setRecipient(Message.RecipientType.TO, new InternetAddress(addressee)); //郵件標題 message.setSubject(title); //郵件內容,前內容,後格式 message.setContent(content, "text/html;charset=UTF-8"); //5.發送郵件 transport.sendMessage(message, message.getAllRecipients()); //6.關閉連接 transport.close(); } }
(本文僅作個人學習記錄用,如有紕漏敬請指正)