JavaMail學習筆記(三)使用SMTP協議發送電子郵件

 

 

  1. package org.yangxin.study.jm; 
  2.  
  3. import java.io.File; 
  4. import java.io.FileInputStream; 
  5. import java.io.FileNotFoundException; 
  6. import java.io.FileOutputStream; 
  7. import java.io.IOException; 
  8. import java.io.InputStream; 
  9. import java.util.Date; 
  10. import java.util.Properties; 
  11.  
  12. import javax.activation.DataHandler; 
  13. import javax.activation.DataSource; 
  14. import javax.activation.FileDataSource; 
  15. import javax.mail.Address; 
  16. import javax.mail.Authenticator; 
  17. import javax.mail.Message; 
  18. import javax.mail.Message.RecipientType;
  19. import javax.mail.MessagingException; 
  20. import javax.mail.PasswordAuthentication;
  21. import javax.mail.Session; 
  22. import javax.mail.Transport; 
  23. import javax.mail.internet.InternetAddress; 
  24. import javax.mail.internet.MimeBodyPart; 
  25. import javax.mail.internet.MimeMessage; 
  26. import javax.mail.internet.MimeMultipart; 
  27. import javax.mail.internet.MimeUtility; 
  28.  
  29. /**
  30. * 使用SMTP協議發送電子郵件
  31. */ 
  32. public class SendMailTest { 
  33.      
  34.     // 郵件發送協議 
  35.     private final static String PROTOCOL = "smtp"
  36.      
  37.     // SMTP郵件服務器 
  38.     private final static String HOST = "smtp.sina.com"
  39.      
  40.     // SMTP郵件服務器默認端口 
  41.     private final static String PORT = "25"
  42.      
  43.     // 是否要求身份認證 
  44.     private final static String IS_AUTH = "true"
  45.      
  46.     // 是否啓用調試模式(啓用調試模式可打印客戶端與服務器交互過程時一問一答的響應消息) 
  47.     private final static String IS_ENABLED_DEBUG_MOD = "true"
  48.      
  49.     // 發件人 
  50.     private static String from = "[email protected]"
  51.  
  52.     // 收件人 
  53.     private static String to = "[email protected]"
  54.      
  55.     // 初始化連接郵件服務器的會話信息 
  56.     private static Properties props = null
  57.      
  58.     static
  59.         props = new Properties(); 
  60.         props.setProperty("mail.transport.protocol", PROTOCOL); 
  61.         props.setProperty("mail.smtp.host", HOST); 
  62.         props.setProperty("mail.smtp.port", PORT); 
  63.         props.setProperty("mail.smtp.auth", IS_AUTH); 
  64.         props.setProperty("mail.debug",IS_ENABLED_DEBUG_MOD); 
  65.     } 
  66.  
  67.     public static void main(String[] args) throws Exception { 
  68.         // 發送文本郵件 
  69.         sendTextEmail(); 
  70.          
  71.         // 發送簡單的html郵件 
  72.         sendHtmlEmail(); 
  73.          
  74.         // 發送帶內嵌圖片的HTML郵件 
  75.         sendHtmlWithInnerImageEmail(); 
  76.          
  77.         // 發送混合組合郵件 
  78.         sendMultipleEmail(); 
  79.          
  80.         // 發送已經生成的eml郵件 
  81.         //sendMailForEml(); 
  82.     } 
  83.      
  84.     /**
  85.      * 發送簡單的文本郵件
  86.      */ 
  87.     public static void sendTextEmail() throws Exception { 
  88.         // 創建Session實例對象 
  89.         Session session = Session.getDefaultInstance(props); 
  90.          
  91.         // 創建MimeMessage實例對象 
  92.         MimeMessage message = new MimeMessage(session); 
  93.         // 設置發件人 
  94.         message.setFrom(new InternetAddress(from)); 
  95.         // 設置郵件主題 
  96.         message.setSubject("使用javamail發送簡單文本郵件"); 
  97.         // 設置收件人 
  98.         message.setRecipient(RecipientType.TO, new InternetAddress(to)); 
  99.         // 設置發送時間 
  100.         message.setSentDate(new Date()); 
  101.         // 設置純文本內容爲郵件正文 
  102.         message.setText("使用POP3協議發送文本郵件測試!!!"); 
  103.         // 保存並生成最終的郵件內容 
  104.         message.saveChanges(); 
  105.          
  106.         // 獲得Transport實例對象 
  107.         Transport transport = session.getTransport(); 
  108.         // 打開連接 
  109.         transport.connect("xyang0917", "123456abc"); 
  110.         // 將message對象傳遞給transport對象,將郵件發送出去 
  111.         transport.sendMessage(message, message.getAllRecipients()); 
  112.         // 關閉連接 
  113.         transport.close(); 
  114.     } 
  115.      
  116.     /**
  117.      * 發送簡單的html郵件
  118.      */ 
  119.     public static void sendHtmlEmail() throws Exception { 
  120.         // 創建Session實例對象 
  121.         Session session = Session.getInstance(props, new MyAuthenticator()); 
  122.          
  123.         // 創建MimeMessage實例對象 
  124.         MimeMessage message = new MimeMessage(session); 
  125.         // 設置郵件主題 
  126.         message.setSubject("html郵件主題"); 
  127.         // 設置發送人 
  128.         message.setFrom(new InternetAddress(from)); 
  129.         // 設置發送時間 
  130.         message.setSentDate(new Date()); 
  131.         // 設置收件人 
  132.         message.setRecipients(RecipientType.TO, InternetAddress.parse(to)); 
  133.         // 設置html內容爲郵件正文,指定MIME類型爲text/html類型,並指定字符編碼爲gbk 
  134.         message.setContent("<span style='color:red;'>html郵件測試...</span>","text/html;charset=gbk"); 
  135.          
  136.         // 保存並生成最終的郵件內容 
  137.         message.saveChanges(); 
  138.          
  139.         // 發送郵件 
  140.         Transport.send(message); 
  141.     } 
  142.      
  143.     /**
  144.      * 發送帶內嵌圖片的HTML郵件
  145.      */ 
  146.     public static void sendHtmlWithInnerImageEmail() throws MessagingException { 
  147.         // 創建Session實例對象 
  148.         Session session = Session.getDefaultInstance(props, new MyAuthenticator()); 
  149.          
  150.         // 創建郵件內容 
  151.         MimeMessage message = new MimeMessage(session); 
  152.         // 郵件主題,並指定編碼格式 
  153.         message.setSubject("帶內嵌圖片的HTML郵件", "utf-8");     
  154.         // 發件人 
  155.         message.setFrom(new InternetAddress(from)); 
  156.         // 收件人 
  157.         message.setRecipients(RecipientType.TO, InternetAddress.parse(to)); 
  158.         // 抄送 
  159.         message.setRecipient(RecipientType.CC, new InternetAddress("[email protected]")); 
  160.         // 密送 (不會在郵件收件人名單中顯示出來) 
  161.         message.setRecipient(RecipientType.BCC, new InternetAddress("[email protected]")); 
  162.         // 發送時間 
  163.         message.setSentDate(new Date()); 
  164.          
  165.         // 創建一個MIME子類型爲“related”的MimeMultipart對象 
  166.         MimeMultipart mp = new MimeMultipart("related"); 
  167.         // 創建一個表示正文的MimeBodyPart對象,並將它加入到前面創建的MimeMultipart對象中 
  168.         MimeBodyPart htmlPart = new MimeBodyPart(); 
  169.         mp.addBodyPart(htmlPart); 
  170.         // 創建一個表示圖片資源的MimeBodyPart對象,將將它加入到前面創建的MimeMultipart對象中 
  171.         MimeBodyPart imagePart = new MimeBodyPart(); 
  172.         mp.addBodyPart(imagePart); 
  173.          
  174.         // 將MimeMultipart對象設置爲整個郵件的內容 
  175.         message.setContent(mp); 
  176.          
  177.         // 設置內嵌圖片郵件體 
  178.         DataSource ds = new FileDataSource(new File("resource/firefoxlogo.png")); 
  179.         DataHandler dh = new DataHandler(ds); 
  180.         imagePart.setDataHandler(dh); 
  181.         imagePart.setContentID("firefoxlogo.png");  // 設置內容編號,用於其它郵件體引用 
  182.          
  183.         // 創建一個MIME子類型爲"alternative"的MimeMultipart對象,並作爲前面創建的htmlPart對象的郵件內容 
  184.         MimeMultipart htmlMultipart = new MimeMultipart("alternative"); 
  185.         // 創建一個表示html正文的MimeBodyPart對象 
  186.         MimeBodyPart htmlBodypart = new MimeBodyPart(); 
  187.         // 其中cid=androidlogo.gif是引用郵件內部的圖片,即imagePart.setContentID("androidlogo.gif");方法所保存的圖片 
  188.         htmlBodypart.setContent("<span style='color:red;'>這是帶內嵌圖片的HTML郵件哦!!!<img src=\"cid:firefoxlogo.png\" /></span>","text/html;charset=utf-8"); 
  189.         htmlMultipart.addBodyPart(htmlBodypart); 
  190.         htmlPart.setContent(htmlMultipart); 
  191.          
  192.         // 保存並生成最終的郵件內容 
  193.         message.saveChanges(); 
  194.          
  195.         // 發送郵件 
  196.         Transport.send(message); 
  197.     } 
  198.      
  199.     /**
  200.      * 發送帶內嵌圖片、附件、多收件人(顯示郵箱姓名)、郵件優先級、閱讀回執的完整的HTML郵件
  201.      */ 
  202.     public static void sendMultipleEmail() throws Exception { 
  203.         String charset = "utf-8";   // 指定中文編碼格式 
  204.         // 創建Session實例對象 
  205.         Session session = Session.getInstance(props,new MyAuthenticator()); 
  206.          
  207.         // 創建MimeMessage實例對象 
  208.         MimeMessage message = new MimeMessage(session); 
  209.         // 設置主題 
  210.         message.setSubject("使用JavaMail發送混合組合類型的郵件測試"); 
  211.         // 設置發送人 
  212.         message.setFrom(new InternetAddress(from,"新浪測試郵箱",charset)); 
  213.         // 設置收件人 
  214.         message.setRecipients(RecipientType.TO,  
  215.                 new Address[] { 
  216.                 // 參數1:郵箱地址,參數2:姓名(在客戶端收件只顯示姓名,而不顯示郵件地址),參數3:姓名中文字符串編碼 
  217.                 new InternetAddress("[email protected]", "張三_sohu", charset), 
  218.                 new InternetAddress("[email protected]", "李四_163", charset), 
  219.             } 
  220.         ); 
  221.         // 設置抄送 
  222.         message.setRecipient(RecipientType.CC, new InternetAddress("[email protected]","王五_gmail",charset)); 
  223.         // 設置密送 
  224.         message.setRecipient(RecipientType.BCC, new InternetAddress("[email protected]", "趙六_QQ", charset)); 
  225.         // 設置發送時間 
  226.         message.setSentDate(new Date()); 
  227.         // 設置回覆人(收件人回覆此郵件時,默認收件人) 
  228.         message.setReplyTo(InternetAddress.parse("\"" + MimeUtility.encodeText("田七") + "\" <[email protected]>")); 
  229.         // 設置優先級(1:緊急   3:普通    5:低) 
  230.         message.setHeader("X-Priority", "1"); 
  231.         // 要求閱讀回執(收件人閱讀郵件時會提示回覆發件人,表明郵件已收到,並已閱讀) 
  232.         message.setHeader("Disposition-Notification-To", from); 
  233.          
  234.         // 創建一個MIME子類型爲"mixed"的MimeMultipart對象,表示這是一封混合組合類型的郵件 
  235.         MimeMultipart mailContent = new MimeMultipart("mixed");  
  236.         message.setContent(mailContent); 
  237.          
  238.         // 附件 
  239.         MimeBodyPart attach1 = new MimeBodyPart(); 
  240.         MimeBodyPart attach2 = new MimeBodyPart(); 
  241.         // 內容 
  242.         MimeBodyPart mailBody = new MimeBodyPart(); 
  243.          
  244.         // 將附件和內容添加到郵件當中 
  245.         mailContent.addBodyPart(attach1); 
  246.         mailContent.addBodyPart(attach2); 
  247.         mailContent.addBodyPart(mailBody); 
  248.          
  249.         // 附件1(利用jaf框架讀取數據源生成郵件體) 
  250.         DataSource ds1 = new FileDataSource("resource/Earth.bmp"); 
  251.         DataHandler dh1 = new DataHandler(ds1); 
  252.         attach1.setFileName(MimeUtility.encodeText("Earth.bmp")); 
  253.         attach1.setDataHandler(dh1); 
  254.          
  255.         // 附件2 
  256.         DataSource ds2 = new FileDataSource("resource/如何學好C語言.txt"); 
  257.         DataHandler dh2 = new DataHandler(ds2); 
  258.         attach2.setDataHandler(dh2); 
  259.         attach2.setFileName(MimeUtility.encodeText("如何學好C語言.txt")); 
  260.          
  261.         // 郵件正文(內嵌圖片+html文本) 
  262.         MimeMultipart body = new MimeMultipart("related");  //郵件正文也是一個組合體,需要指明組合關係 
  263.         mailBody.setContent(body); 
  264.          
  265.         // 郵件正文由html和圖片構成 
  266.         MimeBodyPart imgPart = new MimeBodyPart(); 
  267.         MimeBodyPart htmlPart = new MimeBodyPart(); 
  268.         body.addBodyPart(imgPart); 
  269.         body.addBodyPart(htmlPart); 
  270.          
  271.         // 正文圖片 
  272.         DataSource ds3 = new FileDataSource("resource/firefoxlogo.png"); 
  273.         DataHandler dh3 = new DataHandler(ds3); 
  274.         imgPart.setDataHandler(dh3); 
  275.         imgPart.setContentID("firefoxlogo.png"); 
  276.          
  277.         // html郵件內容 
  278.         MimeMultipart htmlMultipart = new MimeMultipart("alternative");  
  279.         htmlPart.setContent(htmlMultipart); 
  280.         MimeBodyPart htmlContent = new MimeBodyPart(); 
  281.         htmlContent.setContent( 
  282.                 "<span style='color:red'>這是我自己用java mail發送的郵件哦!"
  283.                 "<img src='cid:firefoxlogo.png' /></span>" 
  284.                         , "text/html;charset=gbk"); 
  285.         htmlMultipart.addBodyPart(htmlContent); 
  286.          
  287.         // 保存郵件內容修改 
  288.         message.saveChanges(); 
  289.          
  290.         /*File eml = buildEmlFile(message);
  291.         sendMailForEml(eml);*/ 
  292.          
  293.         // 發送郵件 
  294.         Transport.send(message); 
  295.     } 
  296.      
  297.     /**
  298.      * 將郵件內容生成eml文件
  299.      * @param message 郵件內容
  300.      */ 
  301.     public static File buildEmlFile(Message message) throws MessagingException, FileNotFoundException, IOException { 
  302.         File file = new File("c:\\" + MimeUtility.decodeText(message.getSubject())+".eml"); 
  303.         message.writeTo(new FileOutputStream(file)); 
  304.         return file; 
  305.     } 
  306.      
  307.     /**
  308.      * 發送本地已經生成好的email文件
  309.      */ 
  310.     public static void sendMailForEml(File eml) throws Exception { 
  311.         // 獲得郵件會話 
  312.         Session session = Session.getInstance(props,new MyAuthenticator()); 
  313.         // 獲得郵件內容,即發生前生成的eml文件 
  314.         InputStream is = new FileInputStream(eml); 
  315.         MimeMessage message = new MimeMessage(session,is); 
  316.         //發送郵件 
  317.         Transport.send(message); 
  318.     } 
  319.      
  320.     /**
  321.      * 向郵件服務器提交認證信息
  322.      */ 
  323.     static class MyAuthenticator extends Authenticator { 
  324.          
  325.         private String username = "xyang0917"
  326.          
  327.         private String password = "123456abc"
  328.          
  329.         public MyAuthenticator() { 
  330.             super(); 
  331.         } 
  332.  
  333.         public MyAuthenticator(String username, String password) { 
  334.             super(); 
  335.             this.username = username; 
  336.             this.password = password; 
  337.         } 
  338.  
  339.         @Override 
  340.         protected PasswordAuthentication getPasswordAuthentication() { 
  341.              
  342.             return new PasswordAuthentication(username, password); 
  343.         } 
  344.     } 
package org.yangxin.study.jm;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
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;
import javax.mail.internet.MimeUtility;

/**
 * 使用SMTP協議發送電子郵件
 */
public class SendMailTest {
	
	// 郵件發送協議
	private final static String PROTOCOL = "smtp";
	
	// SMTP郵件服務器
	private final static String HOST = "smtp.sina.com";
	
	// SMTP郵件服務器默認端口
	private final static String PORT = "25";
	
	// 是否要求身份認證
	private final static String IS_AUTH = "true";
	
	// 是否啓用調試模式(啓用調試模式可打印客戶端與服務器交互過程時一問一答的響應消息)
	private final static String IS_ENABLED_DEBUG_MOD = "true";
	
	// 發件人
	private static String from = "[email protected]";

	// 收件人
	private static String to = "[email protected]";
	
	// 初始化連接郵件服務器的會話信息
	private static Properties props = null;
	
	static {
		props = new Properties();
		props.setProperty("mail.transport.protocol", PROTOCOL);
		props.setProperty("mail.smtp.host", HOST);
		props.setProperty("mail.smtp.port", PORT);
		props.setProperty("mail.smtp.auth", IS_AUTH);
		props.setProperty("mail.debug",IS_ENABLED_DEBUG_MOD);
	}

	public static void main(String[] args) throws Exception {
		// 發送文本郵件
		sendTextEmail();
		
		// 發送簡單的html郵件
		sendHtmlEmail();
		
		// 發送帶內嵌圖片的HTML郵件
		sendHtmlWithInnerImageEmail();
		
		// 發送混合組合郵件
		sendMultipleEmail();
		
		// 發送已經生成的eml郵件
		//sendMailForEml();
	}
	
	/**
	 * 發送簡單的文本郵件
	 */
	public static void sendTextEmail() throws Exception {
		// 創建Session實例對象
		Session session = Session.getDefaultInstance(props);
		
		// 創建MimeMessage實例對象
		MimeMessage message = new MimeMessage(session);
		// 設置發件人
		message.setFrom(new InternetAddress(from));
		// 設置郵件主題
		message.setSubject("使用javamail發送簡單文本郵件");
		// 設置收件人
		message.setRecipient(RecipientType.TO, new InternetAddress(to));
		// 設置發送時間
		message.setSentDate(new Date());
		// 設置純文本內容爲郵件正文
		message.setText("使用POP3協議發送文本郵件測試!!!");
		// 保存並生成最終的郵件內容
		message.saveChanges();
		
		// 獲得Transport實例對象
		Transport transport = session.getTransport();
		// 打開連接
		transport.connect("xyang0917", "123456abc");
		// 將message對象傳遞給transport對象,將郵件發送出去
		transport.sendMessage(message, message.getAllRecipients());
		// 關閉連接
		transport.close();
	}
	
	/**
	 * 發送簡單的html郵件
	 */
	public static void sendHtmlEmail() throws Exception {
		// 創建Session實例對象
		Session session = Session.getInstance(props, new MyAuthenticator());
		
		// 創建MimeMessage實例對象
		MimeMessage message = new MimeMessage(session);
		// 設置郵件主題
		message.setSubject("html郵件主題");
		// 設置發送人
		message.setFrom(new InternetAddress(from));
		// 設置發送時間
		message.setSentDate(new Date());
		// 設置收件人
		message.setRecipients(RecipientType.TO, InternetAddress.parse(to));
		// 設置html內容爲郵件正文,指定MIME類型爲text/html類型,並指定字符編碼爲gbk
		message.setContent("<span style='color:red;'>html郵件測試...</span>","text/html;charset=gbk");
		
		// 保存並生成最終的郵件內容
		message.saveChanges();
		
		// 發送郵件
		Transport.send(message);
	}
	
	/**
	 * 發送帶內嵌圖片的HTML郵件
	 */
	public static void sendHtmlWithInnerImageEmail() throws MessagingException {
		// 創建Session實例對象
		Session session = Session.getDefaultInstance(props, new MyAuthenticator());
		
		// 創建郵件內容
		MimeMessage message = new MimeMessage(session);
		// 郵件主題,並指定編碼格式
		message.setSubject("帶內嵌圖片的HTML郵件", "utf-8");	
		// 發件人
		message.setFrom(new InternetAddress(from));
		// 收件人
		message.setRecipients(RecipientType.TO, InternetAddress.parse(to));
		// 抄送
		message.setRecipient(RecipientType.CC, new InternetAddress("[email protected]"));
		// 密送 (不會在郵件收件人名單中顯示出來)
		message.setRecipient(RecipientType.BCC, new InternetAddress("[email protected]"));
		// 發送時間
		message.setSentDate(new Date());
		
		// 創建一個MIME子類型爲“related”的MimeMultipart對象
		MimeMultipart mp = new MimeMultipart("related");
		// 創建一個表示正文的MimeBodyPart對象,並將它加入到前面創建的MimeMultipart對象中
		MimeBodyPart htmlPart = new MimeBodyPart();
		mp.addBodyPart(htmlPart);
		// 創建一個表示圖片資源的MimeBodyPart對象,將將它加入到前面創建的MimeMultipart對象中
		MimeBodyPart imagePart = new MimeBodyPart();
		mp.addBodyPart(imagePart);
		
		// 將MimeMultipart對象設置爲整個郵件的內容
		message.setContent(mp);
		
		// 設置內嵌圖片郵件體
		DataSource ds = new FileDataSource(new File("resource/firefoxlogo.png"));
		DataHandler dh = new DataHandler(ds);
		imagePart.setDataHandler(dh);
		imagePart.setContentID("firefoxlogo.png");	// 設置內容編號,用於其它郵件體引用
		
		// 創建一個MIME子類型爲"alternative"的MimeMultipart對象,並作爲前面創建的htmlPart對象的郵件內容
		MimeMultipart htmlMultipart = new MimeMultipart("alternative");
		// 創建一個表示html正文的MimeBodyPart對象
		MimeBodyPart htmlBodypart = new MimeBodyPart();
		// 其中cid=androidlogo.gif是引用郵件內部的圖片,即imagePart.setContentID("androidlogo.gif");方法所保存的圖片
		htmlBodypart.setContent("<span style='color:red;'>這是帶內嵌圖片的HTML郵件哦!!!<img src=\"cid:firefoxlogo.png\" /></span>","text/html;charset=utf-8");
		htmlMultipart.addBodyPart(htmlBodypart);
		htmlPart.setContent(htmlMultipart);
		
		// 保存並生成最終的郵件內容
		message.saveChanges();
		
		// 發送郵件
		Transport.send(message);
	}
	
	/**
	 * 發送帶內嵌圖片、附件、多收件人(顯示郵箱姓名)、郵件優先級、閱讀回執的完整的HTML郵件
	 */
	public static void sendMultipleEmail() throws Exception {
		String charset = "utf-8";	// 指定中文編碼格式
		// 創建Session實例對象
		Session session = Session.getInstance(props,new MyAuthenticator());
		
		// 創建MimeMessage實例對象
		MimeMessage message = new MimeMessage(session);
		// 設置主題
		message.setSubject("使用JavaMail發送混合組合類型的郵件測試");
		// 設置發送人
		message.setFrom(new InternetAddress(from,"新浪測試郵箱",charset));
		// 設置收件人
		message.setRecipients(RecipientType.TO, 
				new Address[] {
				// 參數1:郵箱地址,參數2:姓名(在客戶端收件只顯示姓名,而不顯示郵件地址),參數3:姓名中文字符串編碼
				new InternetAddress("[email protected]", "張三_sohu", charset),
				new InternetAddress("[email protected]", "李四_163", charset),
			}
		);
		// 設置抄送
		message.setRecipient(RecipientType.CC, new InternetAddress("[email protected]","王五_gmail",charset));
		// 設置密送
		message.setRecipient(RecipientType.BCC, new InternetAddress("[email protected]", "趙六_QQ", charset));
		// 設置發送時間
		message.setSentDate(new Date());
		// 設置回覆人(收件人回覆此郵件時,默認收件人)
		message.setReplyTo(InternetAddress.parse("\"" + MimeUtility.encodeText("田七") + "\" <[email protected]>"));
		// 設置優先級(1:緊急	3:普通	5:低)
		message.setHeader("X-Priority", "1");
		// 要求閱讀回執(收件人閱讀郵件時會提示回覆發件人,表明郵件已收到,並已閱讀)
		message.setHeader("Disposition-Notification-To", from);
		
		// 創建一個MIME子類型爲"mixed"的MimeMultipart對象,表示這是一封混合組合類型的郵件
		MimeMultipart mailContent = new MimeMultipart("mixed");	
		message.setContent(mailContent);
		
		// 附件
		MimeBodyPart attach1 = new MimeBodyPart();
		MimeBodyPart attach2 = new MimeBodyPart();
		// 內容
		MimeBodyPart mailBody = new MimeBodyPart();
		
		// 將附件和內容添加到郵件當中
		mailContent.addBodyPart(attach1);
		mailContent.addBodyPart(attach2);
		mailContent.addBodyPart(mailBody);
		
		// 附件1(利用jaf框架讀取數據源生成郵件體)
		DataSource ds1 = new FileDataSource("resource/Earth.bmp");
		DataHandler dh1 = new DataHandler(ds1);
		attach1.setFileName(MimeUtility.encodeText("Earth.bmp"));
		attach1.setDataHandler(dh1);
		
		// 附件2
		DataSource ds2 = new FileDataSource("resource/如何學好C語言.txt");
		DataHandler dh2 = new DataHandler(ds2);
		attach2.setDataHandler(dh2);
		attach2.setFileName(MimeUtility.encodeText("如何學好C語言.txt"));
		
		// 郵件正文(內嵌圖片+html文本)
		MimeMultipart body = new MimeMultipart("related");	//郵件正文也是一個組合體,需要指明組合關係
		mailBody.setContent(body);
		
		// 郵件正文由html和圖片構成
		MimeBodyPart imgPart = new MimeBodyPart();
		MimeBodyPart htmlPart = new MimeBodyPart();
		body.addBodyPart(imgPart);
		body.addBodyPart(htmlPart);
		
		// 正文圖片
		DataSource ds3 = new FileDataSource("resource/firefoxlogo.png");
		DataHandler dh3 = new DataHandler(ds3);
		imgPart.setDataHandler(dh3);
		imgPart.setContentID("firefoxlogo.png");
		
		// html郵件內容
		MimeMultipart htmlMultipart = new MimeMultipart("alternative");	
		htmlPart.setContent(htmlMultipart);
		MimeBodyPart htmlContent = new MimeBodyPart();
		htmlContent.setContent(
				"<span style='color:red'>這是我自己用java mail發送的郵件哦!" +
				"<img src='cid:firefoxlogo.png' /></span>"
						, "text/html;charset=gbk");
		htmlMultipart.addBodyPart(htmlContent);
		
		// 保存郵件內容修改
		message.saveChanges();
		
		/*File eml = buildEmlFile(message);
		sendMailForEml(eml);*/
		
		// 發送郵件
		Transport.send(message);
	}
	
	/**
	 * 將郵件內容生成eml文件
	 * @param message 郵件內容
	 */
	public static File buildEmlFile(Message message) throws MessagingException, FileNotFoundException, IOException {
		File file = new File("c:\\" + MimeUtility.decodeText(message.getSubject())+".eml");
		message.writeTo(new FileOutputStream(file));
		return file;
	}
	
	/**
	 * 發送本地已經生成好的email文件
	 */
	public static void sendMailForEml(File eml) throws Exception {
		// 獲得郵件會話
		Session session = Session.getInstance(props,new MyAuthenticator());
		// 獲得郵件內容,即發生前生成的eml文件
		InputStream is = new FileInputStream(eml);
		MimeMessage message = new MimeMessage(session,is);
		//發送郵件
		Transport.send(message);
	}
	
	/**
	 * 向郵件服務器提交認證信息
	 */
	static class MyAuthenticator extends Authenticator {
		
		private String username = "xyang0917";
		
		private String password = "123456abc";
		
		public MyAuthenticator() {
			super();
		}

		public MyAuthenticator(String username, String password) {
			super();
			this.username = username;
			this.password = password;
		}

		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			
			return new PasswordAuthentication(username, password);
		}
	}
}

測試結果:


1、發送文本郵件



2、發送簡單的html郵件


3、發送帶內嵌圖片的HTML郵件


4、發送混合組合郵件

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章