天天看點

Java之——Java mail郵件開發實戰

今天,給大家具體講講如何利用java mail實作發送郵箱的功能,不多說了,我們直接進入主題。

一、準備環境

 java發送郵件需要3個jar包的支援,分别是activation.jar,additionnal.jar,mail.jar,大家可以到連結http://download.csdn.net/detail/l1028386804/9490320下載下傳這些所需的jar包,将這些jar包放入到自己的java工程中。

二、實作

1、建立郵件資訊類MailSenderInfo

這個類是發送郵件的基本資訊類,存儲了發送郵件的各種資訊,包括發送郵件的伺服器位址、端口,發送者的郵箱、賬号、密碼、接收者的郵箱和郵件内容等資訊。

具體代碼如下:

package com.lyz.utils.email;

import java.util.Properties;

/**
 * 郵件發送資訊類
 * @author liuyazhuang
 *
 */
public class MailSenderInfo {
	// 發送郵件的伺服器的IP和端口
	private String mailServerHost;
	private String mailServerPort = "25";

	// 郵件發送者的位址
	private String fromAddress;
	// 郵件接收者的位址
	private String toAddress;
	// 登陸郵件發送伺服器的使用者名和密碼
	private String userName;
	private String password;
	// 是否需要身份驗證
	private boolean validate = true;
	// 郵件主題
	private String subject;
	// 郵件的文本内容
	private String content;
	// 郵件附件的檔案名
	private String[] attachFileNames;

	/**
	 * 獲得郵件會話屬性
	 */
	public Properties getProperties() {
		Properties p = new Properties();
		p.put("mail.smtp.host", this.mailServerHost);
		p.put("mail.smtp.port", this.mailServerPort);
		p.put("mail.smtp.auth", validate ? "true" : "false");
		
		p.put("mail.smtp.socketFactory.port", "465");  
		p.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");  
		p.put("mail.smtp.socketFactory.fallback", "false");  
		p.setProperty("mail.smtp.quitwait", "false");
		return p;
	}
	
	public MailSenderInfo() {
		super();
	}
	
	
	public MailSenderInfo(String mailServerHost, String mailServerPort,
			String fromAddress, String toAddress, String userName,
			String password, boolean validate, String subject, String content) {
		super();
		this.mailServerHost = mailServerHost;
		this.mailServerPort = mailServerPort;
		this.fromAddress = fromAddress;
		this.toAddress = toAddress;
		this.userName = userName;
		this.password = password;
		this.validate = validate;
		this.subject = subject;
		this.content = content;
	}

	public String getMailServerHost() {
		return mailServerHost;
	}

	public void setMailServerHost(String mailServerHost) {
		this.mailServerHost = mailServerHost;
	}

	public String getMailServerPort() {
		return mailServerPort;
	}

	public void setMailServerPort(String mailServerPort) {
		this.mailServerPort = mailServerPort;
	}

	public boolean isValidate() {
		return validate;
	}

	public void setValidate(boolean validate) {
		this.validate = validate;
	}

	public String[] getAttachFileNames() {
		return attachFileNames;
	}

	public void setAttachFileNames(String[] fileNames) {
		this.attachFileNames = fileNames;
	}

	public String getFromAddress() {
		return fromAddress;
	}

	public void setFromAddress(String fromAddress) {
		this.fromAddress = fromAddress;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getToAddress() {
		return toAddress;
	}

	public void setToAddress(String toAddress) {
		this.toAddress = toAddress;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String textContent) {
		this.content = textContent;
	}
}
           

2、建立發送郵件的認證類MyAuthenticator

這個類是發送郵件時的認證類,此類繼承自Authenticator。

package com.lyz.utils.email;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
 * 發送郵件的認證類
 * @author liuyazhuang
 *
 */
public class MyAuthenticator extends Authenticator {
	String userName = null;
	String password = null;

	public MyAuthenticator() {
	}

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

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(userName, password);
	}
}
           

3、建立發送郵件的核心類MailSender

這個類是整個項目的核心,是整個項目的郵件發送器。這個類共實作了4個方法:

(1)以文本格式發送郵件,不帶附件的sendTextMail方法;

(2)以帶附件的方式發送文本格式郵件的sendTextMailWithAttachment方法

(3)以HTML格式發送郵件,帶附件的sendHtmlMailWithAttachment方法

(4)以HTML格式發送郵件,不帶附件的sendHtmlMail方法

package com.lyz.utils.email;

import java.util.Date;
import java.util.Properties;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.Address;
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;

/**
 * @author liuyazhuang
 * 郵件發送器
 */
public class MailSender {
	
	
	/**
	 * 以文本格式發送郵件,不帶附件
	 * @param mailInfo
	 *            待發送的郵件的資訊
	 */
	public static boolean sendTextMail(MailSenderInfo mailInfo) {
		// 判斷是否需要身份認證
		MyAuthenticator authenticator = null;
		Properties pro = mailInfo.getProperties();
		if (mailInfo.isValidate()) {
			// 如果需要身份認證,則建立一個密碼驗證器
			authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
		}
		// 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
		Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
		try {
			// 根據session建立一個郵件消息
			Message mailMessage = new MimeMessage(sendMailSession);
			// 建立郵件發送者位址
			Address from = new InternetAddress(mailInfo.getFromAddress());
			// 設定郵件消息的發送者
			mailMessage.setFrom(from);
			// 建立郵件的接收者位址,并設定到郵件消息中
			Address to = new InternetAddress(mailInfo.getToAddress());
			mailMessage.setRecipient(Message.RecipientType.TO, to);
			// 設定郵件消息的主題
			mailMessage.setSubject(mailInfo.getSubject());
			// 設定郵件消息發送的時間
			mailMessage.setSentDate(new Date());
			// 設定郵件消息的主要内容
			String mailContent = mailInfo.getContent();
			mailMessage.setText(mailContent);
			MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
	        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
	        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
	        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
	        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
	        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
	        CommandMap.setDefaultCommandMap(mc);
			// 發送郵件
			Transport.send(mailMessage);
			return true;
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}
		return false;
	}
	
	
	/**
	 * 以帶附件的方式發送文本格式郵件
	 * @param mailInfo 待發送的郵件的資訊
	 * @param filenames 附件的磁盤絕對路徑
	 */
	public static boolean sendTextMailWithAttachment(MailSenderInfo mailInfo, String ... filenames) {
		// 判斷是否需要身份認證
		MyAuthenticator authenticator = null;
		Properties pro = mailInfo.getProperties();
		if (mailInfo.isValidate()) {
			// 如果需要身份認證,則建立一個密碼驗證器
			authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
		}
		// 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
		Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
		try {
			// 根據session建立一個郵件消息
			Message mailMessage = new MimeMessage(sendMailSession);
			// 建立郵件發送者位址
			Address from = new InternetAddress(mailInfo.getFromAddress());
			// 設定郵件消息的發送者
			mailMessage.setFrom(from);
			// 建立郵件的接收者位址,并設定到郵件消息中
			Address to = new InternetAddress(mailInfo.getToAddress());
			mailMessage.setRecipient(Message.RecipientType.TO, to);
			// 設定郵件消息的主題
			mailMessage.setSubject(mailInfo.getSubject());
			// 設定郵件消息發送的時間
			mailMessage.setSentDate(new Date());
			//執行個體化Multipart
			Multipart mp = new MimeMultipart();
			//執行個體化發送文本的MimeBodyPart
			MimeBodyPart textFile = new MimeBodyPart();
			//設定文本資訊
			textFile.setText(mailInfo.getContent(), "UTF-8");
			mp.addBodyPart(textFile);
			//是否添加了附件
			if(filenames != null && filenames.length > 0){
				for(int i = 0; i < filenames.length; i++){
					String fileName = filenames[i];
					//檔案名為空,跳過本次循環
					if(fileName == null || "".equals(fileName.trim())){
						continue;
					}
					MimeBodyPart mbpFile = new MimeBodyPart();
					FileDataSource fds = new FileDataSource(fileName);
					mbpFile.setDataHandler(new DataHandler(fds));
					mbpFile.setFileName(fileName);
					mp.addBodyPart(mbpFile);
				}
			}
			mailMessage.setContent(mp);
			MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
	        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
	        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
	        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
	        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
	        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
	        CommandMap.setDefaultCommandMap(mc);
			// 發送郵件
			Transport.send(mailMessage);
			return true;
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}
		return false;
	}

	/**
	 * 以HTML格式發送郵件,帶附件
	 * @param mailInfo
	 *            待發送的郵件資訊
	 *  @param filenames:附件在磁盤上的絕對路徑
	 */
	public static boolean sendHtmlMailWithAttachment(MailSenderInfo mailInfo, String... filenames) {
		// 判斷是否需要身份認證
		MyAuthenticator authenticator = null;
		Properties pro = mailInfo.getProperties();
		// 如果需要身份認證,則建立一個密碼驗證器
		if (mailInfo.isValidate()) {
			authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
		}
		// 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
		Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
		try {
			// 根據session建立一個郵件消息
			Message mailMessage = new MimeMessage(sendMailSession);
			// 建立郵件發送者位址
			Address from = new InternetAddress(mailInfo.getFromAddress());
			// 設定郵件消息的發送者
			mailMessage.setFrom(from);
			// 建立郵件的接收者位址,并設定到郵件消息中
			Address to = new InternetAddress(mailInfo.getToAddress());
			// Message.RecipientType.TO屬性表示接收者的類型為TO
			mailMessage.setRecipient(Message.RecipientType.TO, to);
			// 設定郵件消息的主題
			mailMessage.setSubject(mailInfo.getSubject());
			// 設定郵件消息發送的時間
			mailMessage.setSentDate(new Date());
			// MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象
			Multipart mainPart = new MimeMultipart();
			// 建立一個包含HTML内容的MimeBodyPart
			BodyPart html = new MimeBodyPart();
			// 設定HTML内容
			html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
			mainPart.addBodyPart(html);
			//是否添加了附件
			if(filenames != null && filenames.length > 0){
				for(int i = 0; i < filenames.length; i++){
					String fileName = filenames[i];
					//檔案名為空,跳過本次循環
					if(fileName == null || "".equals(fileName.trim())){
						continue;
					}
					MimeBodyPart mbpFile = new MimeBodyPart();
					FileDataSource fds = new FileDataSource(fileName);
					mbpFile.setDataHandler(new DataHandler(fds));
					mbpFile.setFileName(fileName);
					mainPart.addBodyPart(mbpFile);
				}
			}
			// 将MiniMultipart對象設定為郵件内容
			mailMessage.setContent(mainPart);
			MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
	        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
	        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
	        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
	        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
	        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
	        CommandMap.setDefaultCommandMap(mc);
			// 發送郵件
			Transport.send(mailMessage);
			return true;
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}
		return false;
	}
	/**
	 * 以HTML格式發送郵件
	 * @param mailInfo
	 *            待發送的郵件資訊
	 */
	public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
		// 判斷是否需要身份認證
		MyAuthenticator authenticator = null;
		Properties pro = mailInfo.getProperties();
		// 如果需要身份認證,則建立一個密碼驗證器
		if (mailInfo.isValidate()) {
			authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
		}
		// 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
		Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
		try {
			// 根據session建立一個郵件消息
			Message mailMessage = new MimeMessage(sendMailSession);
			// 建立郵件發送者位址
			Address from = new InternetAddress(mailInfo.getFromAddress());
			// 設定郵件消息的發送者
			mailMessage.setFrom(from);
			// 建立郵件的接收者位址,并設定到郵件消息中
			Address to = new InternetAddress(mailInfo.getToAddress());
			// Message.RecipientType.TO屬性表示接收者的類型為TO
			mailMessage.setRecipient(Message.RecipientType.TO, to);
			// 設定郵件消息的主題
			mailMessage.setSubject(mailInfo.getSubject());
			// 設定郵件消息發送的時間
			mailMessage.setSentDate(new Date());
			// MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象
			Multipart mainPart = new MimeMultipart();
			// 建立一個包含HTML内容的MimeBodyPart
			BodyPart html = new MimeBodyPart();
			// 設定HTML内容
			html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
			mainPart.addBodyPart(html);
			// 将MiniMultipart對象設定為郵件内容
			mailMessage.setContent(mainPart);
			MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
	        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
	        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
	        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
	        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
	        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
	        CommandMap.setDefaultCommandMap(mc);
			// 發送郵件
			Transport.send(mailMessage);
			return true;
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}
		return false;
	}
}
           

4、建立配置檔案email.properties

為了更加符合程式設計的規範,這裡我們将發送郵件必須要用到的一些資訊放到一個配置檔案中,在項目的classpath目錄下建立email.properties檔案。

具體代碼如下:

mail_server_host = smtp.qq.com
mail_server_port = 995
mail_user_name = your username
mail_password = your password
mail_from_address = your email where send email           

注:大家要将檔案中的使用者名、密碼、和發送郵件的郵箱替換為自己的使用者名、密碼和發送郵件的郵箱。

5、建立測試類SendTest

這個類是整個項目的測試類,測試是否能夠實作發送郵件的功能

package com.lyz.utils.test;

import java.io.InputStream;
import java.util.Properties;

import com.lyz.utils.email.MailSender;
import com.lyz.utils.email.MailSenderInfo;

/**
 * 測試發送郵件
 * @author liuyazhuang
 *
 */
public class SendTest {

	/**
	 * 
	 *  QQ郵箱 POP3 和 SMTP 伺服器位址設定如下:郵箱POP3伺服器(端口110)SMTP伺服器(端口25)qq.com pop.qq.com smtp.qq.comSMTP伺服器需要身份驗證。
		如果是設定POP3和SMTP的SSL加密方式,則端口如下:
		POP3伺服器(端口995)
		SMTP伺服器(端口465或587)。
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		Properties prop = new Properties();
		InputStream in = SendTest.class.getResourceAsStream("/email.properties");
		prop.load(in);
		
		MailSenderInfo mailInfo = new MailSenderInfo();
		mailInfo.setMailServerHost(prop.getProperty("mail_server_host"));
		mailInfo.setMailServerPort(prop.getProperty("mail_server_port"));
		mailInfo.setUserName(prop.getProperty("mail_user_name"));
		mailInfo.setPassword(prop.getProperty("mail_password"));
		mailInfo.setFromAddress(prop.getProperty("mail_from_address"));
		
		mailInfo.setValidate(true);
		mailInfo.setToAddress("你要發送郵件的目标郵箱");
		mailInfo.setSubject("你好");
		mailInfo.setContent("我叫劉亞壯");
		
		// 這個類主要來發送郵件
		MailSender.sendTextMailWithAttachment(mailInfo);// 發送文體格式
	}

}
           

三、運作效果

四、附錄

繼續閱讀