mport java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class SendMail {
// 發件人郵箱地址
private static String from = "xxxx@163.com";
// 發件人稱號,同郵箱地址
private static String user = "xxxx@163.com";
// 發件人郵箱客戶端授權碼
private static String password = "xxxx";
//發件人的郵箱服務器
private static String mailHost = "smtp.163.com";
/**
* @param to
* @param text
* @param title
*/
/* 發送驗證信息的郵件 */
public static boolean sendMail(String to, String text, String title) {
Properties props = new Properties();
// 設置發送郵件的郵件服務器的屬性(這里使用網易的smtp服務器)
props.put("mail.smtp.host", mailHost);
// 需要經過授權,也就是有戶名和密碼的校驗,這樣才能通過驗證(一定要有這一條)
props.put("mail.smtp.auth", "true");
// 用剛剛設置好的props對象構建一個session
Session session = Session.getDefaultInstance(props);
// 有了這句便可以在發送郵件的過程中在console處顯示過程信息,供調試使用(你可以在控制台(console)上看到發送郵件的過程)
// session.setDebug(true);
// 用session為參數定義消息對象
MimeMessage message = new MimeMessage(session);
try {
// 加載發件人地址
message.setFrom(new InternetAddress(from));
// 加載收件人地址
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// 加載標題
message.setSubject(title);
// 向multipart對象中添加郵件的各個部分內容,包括文本內容和附件
Multipart multipart = new MimeMultipart();
// 設置郵件的文本內容
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(text, "text/html;charset=utf-8");
multipart.addBodyPart(contentPart);
message.setContent(multipart);
message.saveChanges(); // 保存變化
// 連接服務器的郵箱
Transport transport = session.getTransport("smtp");
// 把郵件發送出去
transport.connect(mailHost, user, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("郵件發送成功");
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
return true;
}
public static void main(String[] args) { // 做測試用
//String toMail="xxxxx@fenglinggame.com";
String toMail = "xxx@qq.com";
String text = "你好,<a href='http://www.baidu.com'>激活</a>有驚喜噢";
String title = "測試小通知";
sendMail(toMail, text, title);
}
}
————————————————
版權聲明:本文為CSDN博主「peixinRo」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_42035966/article/details/81332504