剛學習到java郵件相關的知識,先寫下這篇博客,方便以后翻閱學習。
-----------------------------第一步 開啟SMTP服務
在 QQ 郵箱里的 設置->賬戶里開啟 SMTP 服務
完成驗證
獲取授權碼(后面代碼實現時使用)
-----------------------------第二步 環境配置
即下載第三方庫
https://github.com/javaee/javamail/releases
-----------------------------第三步 代碼實現
package com.core; import java.security.GeneralSecurityException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.sun.mail.util.MailSSLSocketFactory; public class MailTool { public static void main(String[] args) throws MessagingException, GeneralSecurityException { 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加密,否則會失敗 MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); props.put("mail.smtp.ssl.enable", "true"); props.put("mail.smtp.ssl.socketFactory", sf); // 創建session Session session = Session.getInstance(props); // 創建郵件 Message msg = new MimeMessage(session); // 設置標題 msg.setSubject("測試郵件"); // 編輯內容 StringBuilder builder = new StringBuilder(); builder.append("這是一封java mail測試郵件\n"); builder.append("這是第二行"); builder.append("\n時間 " + getStringDate()); // 設置內容 msg.setText(builder.toString()); // 發送的郵箱地址 msg.setFrom(new InternetAddress("自己的郵箱@qq.com")); // 通過session得到transport對象 Transport transport = session.getTransport(); // 連接郵件服務器:郵箱類型,帳號,授權碼代替密碼(更安全) transport.connect("smtp.qq.com", "自己的郵箱@qq.com", "授權碼"); // 發送郵件 transport.sendMessage(msg, new Address[] { new InternetAddress("目標郵箱@qq.com") }); transport.close(); } /** * 獲取當前時間 * @return String */ public static String getStringDate() { Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = formatter.format(currentTime); return dateString; } }
-----------------------------第四步 效果展示
-----------------------------第五步 推薦