傳送QQ郵件
阿新 • • 發佈:2018-11-19
import com.sun.mail.util.MailSSLSocketFactory
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart
//--------建立Session 開始-------------
Properties prop = new Properties();
prop.setProperty("mail.smtp.host", "smtp.qq.com") // 指定主機
prop.put("mail.smtp.port", "465")
prop.setProperty("mail.smtp.auth", "true");// 指定驗證為true
MailSSLSocketFactory sf = new MailSSLSocketFactory()
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
// 建立驗證器
Authenticator auth = new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
//密碼為:授權碼
return new PasswordAuthentication(" [email protected]", "xfzljfvaaaffcach");
}
};
Session session =Session.getInstance(prop, auth)
session.setDebug(true)
//--------建立Session 結束-------------
MimeMessage mailMessage = new MimeMessage(session)
mailMessage.setFrom(new InternetAddress(" [email protected]"))
// Message.RecipientType.TO屬性表示接收者的型別為TO
mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
mailMessage.setSubject("這是郵件主題", "UTF-8");
mailMessage.setSentDate(new Date());
// MiniMultipart類是一個容器類,包含MimeBodyPart型別的物件
Multipart mainPart = new MimeMultipart();
// 建立一個包含HTML內容的MimeBodyPart
BodyPart html = new MimeBodyPart();
html.setContent("<a href='https://www.baidu.com'>百度</a>", "text/html; charset=utf-8");
mainPart.addBodyPart(html);
mailMessage.setContent(mainPart);
Transport transport = session.getTransport();
//密碼為:授權碼
transport.connect("smtp.qq.com", 465, " [email protected]", "xfzljfvaaaffcach")
transport.sendMessage(mailMessage, [new InternetAddress("[email protected]")] as Address[])
transport.close()