它将尋找字元串"mail.smtp.host",屬性值就是發送郵件的主機.
public static void main(string[] args) throws exception {
properties properties = new properties();
// properties.put("mail.smtp.host", "mailcas.chinapnr.com");// 設定smtp主機
properties.put("mail.smtp.host", "smtp.163.com");// 設定smtp主機
properties.put("mail.smtp.auth", "true");// 使用smtp身份驗證
/*
* 在 javamail 中,能夠通過 extends authenticator 抽象類,在子類中覆寫父類中的
* getpasswordauthentication() 方法,就能夠實作以不同的方式來進行登入郵箱時的使用者身份認證。
javamail
* 中的這樣的設計是使用了政策模式(strategy
*/
mimemessage message = new mimemessage(session.getinstance(properties,
new authenticator() {
public passwordauthentication getpasswordauthentication() {
return new passwordauthentication(//設定發送帳号password
"帳号", "password");
}
}));
// 設定郵件的屬性
// 設定郵件的發件人
message.setfrom(new internetaddress("發件人"));
// 設定郵件的收件人 cc表示抄送 bcc 表示暗送
message.setrecipient(message.recipienttype.to, new internetaddress(
"收件人"));
// 設定郵件的主題
message.setsubject("系統自己主動發送郵件");
// 建立郵件的正文
mimebodypart text = new mimebodypart();
// setcontent(“郵件的正文内容”,”設定郵件内容的編碼方式”)
text.setcontent("此郵件為系統自己主動發送<img src='cid:a'><img src='cid:b'>",
"text/html;charset=gb2312");
// 點到點的發送
// 一對多發送僅僅要改一個地方例如以下:
// // 建構一個群發位址數組
// internetaddress[] adr=new internetaddress[tomore.length];
// for(int i=0;i<tomore.length;i++){ adr[i]=new
// internetaddress(tomore[i]); }
// // message的setrecipients方法支援群發。
。注意:setrecipients方法是複數和點 到點不一樣
// message.setrecipients(message.recipienttype.to,adr);
// 建立圖檔
mimebodypart img = new mimebodypart();
* javamail api不限制資訊僅僅為文本,不論什麼形式的資訊都可能作繭自縛mimemessage的一部分.
* 除了文本資訊,作為檔案附件包括在電子郵件資訊的一部分是非常普遍的. javamail
* api通過使用datahandler對象,提供一個同意我們包括非文本bodypart對象的簡便方法.
datahandler dh = new datahandler(new filedatasource("src//a.jpg"));//圖檔路徑
img.setdatahandler(dh);
// 建立圖檔的一個表示用于顯示在郵件中顯示
img.setcontentid("a");
mimebodypart img2 = new mimebodypart();
datahandler dh2 = new datahandler(new filedatasource("src//b.jpg"));//第二張圖檔路徑
img2.setdatahandler(dh2);
img2.setcontentid("b");
// 建立附件
// mimebodypart attch = new mimebodypart();
// datahandler dh1 = new datahandler(new filedatasource("src//b.jpg"));
// attch.setdatahandler(dh1);
// string filename1 = dh1.getname();
// mimeutility 是一個工具類。encodetext()用于處理附件字。防止中文亂碼問題
// attch.setfilename(mimeutility.encodetext(filename1));
// 關系 正文和圖檔的
mimemultipart mm = new mimemultipart();
mm.addbodypart(text);
mm.addbodypart(img);
mm.setsubtype("related");// 設定正文與圖檔之間的關系
// 圖班與正文的 body
mimebodypart all = new mimebodypart();
all.setcontent(mm);
// 附件與正文(text 和 img)的關系
mimemultipart mm2 = new mimemultipart();
mm2.addbodypart(all);
mm2.addbodypart(img2);
mm2.setsubtype("mixed");// 設定正文與附件之間的關系
message.setcontent(mm2);
message.savechanges(); // 儲存改動
transport.send(message);// 發送郵件
system.out.println("郵件發送成功");
java發送帶圖檔的郵件,代碼為發生2張圖檔的郵件關聯方式。凝視中有發送帶附件、帶多人發送解析的代碼,能夠自行調整