Java 基於JavaMail實現QQ郵件發送(也可實現羣發)

1.開啓SMTP服務
在 QQ 郵箱裏的 設置->賬戶裏開啓 SMTP 服務


注意開啓完之後,QQ 郵箱會生成一個授權碼,在代碼裏連接郵箱使用這個授權碼而不是原始的郵箱密碼,這樣可以避免使用明文密碼。

2.下載依賴的 jar 包
解壓完之後,通常我們只需要其中的mail.jar,把它加到 工程的依賴包中。

3.完整代碼示例
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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.getInstance(props);

Message msg = new MimeMessage(session);
msg.setSubject("seenews 錯誤");
StringBuilder builder = new StringBuilder();
builder.append("url = " + "http://blog.csdn.net/never_cxb/article/details/50524571");
builder.append("\n頁面爬蟲錯誤");
builder.append("\n時間 " + new Date());
msg.setText(builder.toString());
msg.setFrom(new InternetAddress("發送人的郵箱地址"));//**發送人的郵箱地址**

Transport transport = session.getTransport();
transport.connect("smtp.qq.com","發送人的郵箱地址","你的郵箱授權碼");
List<String> list=new ArrayList<>();
//實現羣發,下面的方法也是可以實現羣發,但是不太理想
transport.sendMessage(msg, InternetAddress.parse("[email protected],[email protected]"));
/*transport.sendMessage(msg, new Address[] {
new InternetAddress("[email protected]"),
new InternetAddress("[email protected]"),
new InternetAddress("[email protected]")
}
);*/
transport.close();
}
}

參看文章:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章