前言
相比於java實現短信驗證碼,郵箱驗證碼就簡單了許多,目前只是簡單的利用java發送自定義內容至指定郵箱,等過幾天再弄短信和郵箱驗證碼Web版本的。查詢網上資料,得知相比於網易郵箱,QQ郵箱是最麻煩的,而且平時我個人使用的也是QQ郵箱,所以也是選擇了QQ郵箱。
配置協議
1.首先,我們需要打開發送方的QQ郵箱,也就是你的郵箱,點擊上方的設置。

進入之后,點擊賬戶,下滑至POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務,將POP3/SMTP服務打開即可

開啟服務之后,會獲得一個授權碼,把它記下來,后面寫代碼的時候會用的到。
代碼實現(黃色部分需修改為自己數據)
Mail_Java.java:
package util; import java.util.Properties; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.sun.mail.util.MailSSLSocketFactory; /** * JavaMail發送郵件: java版本-與web無關 * 前提是QQ郵箱里帳號設置要開啟POP3/SMTP協議 * * */ public class Mail_java { public static void main(String[] args) throws Exception { Properties prop = new Properties(); // 開啟debug調試,以便在控制台查看 prop.setProperty("mail.debug", "true"); // 設置郵件服務器主機名 prop.setProperty("mail.host", "smtp.qq.com"); // 發送服務器需要身份驗證 prop.setProperty("mail.smtp.auth", "true"); // 發送郵件協議名稱 prop.setProperty("mail.transport.protocol", "smtp"); // 開啟SSL加密,否則會失敗 MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf); // 創建session Session session = Session.getInstance(prop); // 通過session得到transport對象 Transport ts = session.getTransport(); // 連接郵件服務器:郵箱類型,帳號,POP3/SMTP協議授權碼 163使用:smtp.163.com ts.connect("smtp.qq.com", "發送方的QQ號", "POP3/SMTP協議授權碼"); // 創建郵件 Message message = createSimpleMail(session); // 發送郵件 ts.sendMessage(message, message.getAllRecipients()); ts.close(); } /** * @Method: createSimpleMail * @Description: 創建一封只包含文本的郵件 */ public static MimeMessage createSimpleMail(Session session) throws Exception { // 獲取6為隨機驗證碼 String[] letters = new String[] { "q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m", "A","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M", "0","1","2","3","4","5","6","7","8","9"}; String stringBuilder =""; for (int i = 0; i < 6; i++) { stringBuilder = stringBuilder + letters[(int)Math.floor(Math.random()*letters.length)]; } // 創建郵件對象 MimeMessage message = new MimeMessage(session); // 指明郵件的發件人 message.setFrom(new InternetAddress("發送方QQ@qq.com")); // 指明郵件的收件人,發件人和收件人如果是一樣的,那就是自己給自己發 message.setRecipient(Message.RecipientType.TO, new InternetAddress("接受方QQ@qq.com")); // 郵件的標題 message.setSubject("JavaMail測試"); // 郵件的文本內容 message.setContent("歡迎您注冊【OG高玩會】,賬號注冊驗證碼為(一分鍾有效):"+stringBuilder+",請勿回復此郵箱", "text/html;charset=UTF-8"); // 返回創建好的郵件對象 return message; } }
所需jar包
鏈接:https://pan.baidu.com/s/14PvQvB4hUBUrrk-uTus_6w
提取碼:xeg3
