1.首先應該開通163郵箱的smtp和pop3,得到授權碼
2.其次建立一個web項目,否則需要倒jar包mail.jar
3.創建一個類
4.注意:郵件內容必須爲正式話語,否則系統會認爲是垃圾郵件而拒收,報錯541DT
public static void main(String[] args) throws MessagingException {
Properties prop=new Properties();
prop.put("mail.host","smtp.163.com" );
prop.put("mail.transport.protocol", "smtp");
prop.put("mail.smtp.auth", true);
//1.創建sesssion
Session session=Session.getInstance(prop);
//開啓session的調試模式,可以查看當前郵件發送狀態
session.setDebug(true);
//2.通過session獲取Transport對象(發送郵件的核心API)
Transport ts=session.getTransport();
//3.通過郵件用戶名密碼鏈接
ts.connect("此處應爲用戶名", "此處應爲授權碼");
//4.創建郵件
Message msg=createSimpleMail(session);
//5.發送電子郵件
ts.sendMessage(msg, msg.getAllRecipients());
}
public static MimeMessage createSimpleMail(Session session) throws AddressException,MessagingException{
//創建郵件對象
MimeMessage mm=new MimeMessage(session);
//設置發件人
mm.setFrom(new InternetAddress("用戶名@163.com"));
//設置收件人
mm.setRecipient(Message.RecipientType.TO, new InternetAddress("用戶名@163.com"));
//設置抄送人
mm.setRecipient(Message.RecipientType.CC, new InternetAddress("用戶名@163.com"));
mm.setSubject("第一封JAVA郵件!");
mm.setContent("咱們開會把", "text/html;charset=gbk");
return mm;
}