package com.jetair.testSendMail;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
/**
* Created by 22431 on 2016/8/22.
*/
public class SendMail {
public static void main(String[] args) throws MessagingException {
new SendMail().run();
}
public void run() {
// 跟smtp服務器建立一個連接
Properties prop = new Properties();
// 設置郵件服務器主機名
prop.setProperty("mail.host", "smtp.qq.com");// 指定郵件服務器,默認端口 25
// 發送服務器需要身份驗證
prop.setProperty("mail.smtp.auth", "true");// 要採用指定用戶名密碼的方式去認證
// 發送郵件協議名稱
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.timeout" , "80000");
// 開啓SSL加密,否則會失敗
MailSSLSocketFactory mailSSLSocketFactory = null;
try {
mailSSLSocketFactory = new MailSSLSocketFactory();
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
}
mailSSLSocketFactory.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
// 開啓debug調試,以便在控制檯查看
// session.setDebug(true);也可以這樣設置
// p.setProperty("mail.debug", "true");
// 創建session
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用戶名可以用QQ賬號也可以用郵箱的別名
PasswordAuthentication pa = new PasswordAuthentication(
"2243146624", "gitdldtsbropdiag");
// 後面的字符是授權碼,用qq密碼不行!!
return pa;
}
});
session.setDebug(true);// 設置打開調試狀態
try {
// 聲明一個Message對象(代表一封郵件),從session中創建
MimeMessage msg = new MimeMessage(session);
// 郵件信息封裝
// 1發件人
msg.setFrom(new InternetAddress("[email protected]"));
// 2收件人
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
// 3郵件內容:主題、內容
msg.setSubject( "測試sendMail");
// msg.setContent("<a href=" ">go</a>", "text/html;charset=utf-8");// 發html格式的文本
msg.setText("這只是一個測試,真的就只是一個測試");
// 發送動作
Transport.send(msg);
System.out.println("發送郵件成功");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
sendMail
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.