1. 程式人生 > 實用技巧 >郵件傳送——QQ郵箱代理

郵件傳送——QQ郵箱代理

1.開啟郵件服務

  如果選用QQ郵箱作為代理服務的話,需要進行一些設定:

  登入郵箱後,點選設定->賬戶

        

將四個服務開啟,然後點選生成授權碼,獲取到授權碼以便使用。

2.郵件傳送

  通過java的mail工具包,傳送郵件,話不多說,上程式碼。

  

package ext.plm.mail;

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import
javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage.RecipientType; public class EmailTestSend { public void send(String subject,String content) throws Exception{ // 建立Properties 類用於記錄郵箱的一些屬性
Properties props = new Properties(); // 表示SMTP傳送郵件,必須進行身份驗證 props.put("mail.smtp.auth", "true"); //此處填寫SMTP伺服器 props.put("mail.smtp.host", "smtp.qq.com"); //埠號,QQ郵箱埠587 props.put("mail.smtp.port", "587"); // 此處填寫,寫信人的賬號
props.put("mail.user", "發件人郵箱"); // 此處填寫16位STMP授權碼 props.put("mail.password", "生成的授權碼"); // 構建授權資訊,用於進行SMTP進行身份驗證 Authenticator authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { // 使用者名稱、密碼 String userName = props.getProperty("mail.user"); String password = props.getProperty("mail.password"); return new PasswordAuthentication(userName, password); } }; // 使用環境屬性和授權資訊,建立郵件會話 Session mailSession = Session.getInstance(props, authenticator); // 建立郵件訊息 MimeMessage message = new MimeMessage(mailSession); // 設定發件人 InternetAddress form = new InternetAddress(props.getProperty("mail.user")); message.setFrom(form); // 設定收件人的郵箱 InternetAddress to = new InternetAddress("收件人郵箱"); message.setRecipient(RecipientType.TO, to); // 設定郵件標題 message.setSubject(subject); // 設定郵件的內容體 message.setContent(content, "text/html;charset=UTF-8"); // 最後當然就是傳送郵件啦 Transport.send(message); } }