javamail開發郵件【發送郵件】

用到java開發發送郵件的部分,其實很簡單依賴的jar包有點擊下載(無需積分)

主要是郵箱的服務器的驗證

以下是源碼

都是經過我自己運行才發表的,有任何問題可以留言或者郵箱聯繫我,我會第一時間處理。

 

服務器登陸的安全認證:

 

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

/**
 * 服務器郵箱登錄驗證
 * 
 * @author [email protected]
 * 
 */
public class MailAuthenticator extends Authenticator {

	/**
	 * 用戶名(登錄郵箱)
	 */
	private String username;
	/**
	 * 密碼
	 */
	private String password;

	/**
	 * 初始化郵箱和密碼
	 * 
	 * @param username
	 *            郵箱
	 * @param password
	 *            密碼
	 */
	public MailAuthenticator(String username, String password) {
		this.username = username;
		this.password = password;
	}

	String getPassword() {
		return password;
	}

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

	String getUsername() {
		return username;
	}

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

	public void setUsername(String username) {
		this.username = username;
	}

}


發件箱工廠:

 

 

import java.io.IOException;
import java.util.Properties;

/**
 * 發件箱工廠
 * 
 * @author [email protected]
 * 
 */
public class MailSenderFactory {

	/**
	 * 服務郵箱
	 */
	private static SimpleMailSender serviceSms = null;

	/**
	 * 獲取郵箱
	 * 
	 * @param type
	 *            郵箱類型
	 * @return 符合類型的郵箱
	 * @throws IOException
	 */
	public static SimpleMailSender getSender() throws IOException {
		if (initUser() == null) {
			serviceSms = new SimpleMailSender("[email protected]",
					"test_for_masque");
		}
		return serviceSms;
	}

	private static SimpleMailSender initUser() throws IOException {
		Properties p = PropertiesUtil.getInstance("mail-user.properties");
		if (null == p)
			return null;
		serviceSms = new SimpleMailSender(p.getProperty("user.name"),
				p.getProperty("user.password"));
		return serviceSms;
	}
}


發送郵件用戶名以及密碼我是在文件中配置的

 

 

import java.io.IOException;
import java.util.Properties;

/**
 * 讀取Properties
 * 
 * @author [email protected]
 * 
 */
public class PropertiesUtil {

	static Properties props = new Properties();

	private PropertiesUtil() {
	}

	public static Properties getInstance(String path) throws IOException {
		props.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(
				path));
		return props;
	}

	public static String getProperty(String key) {
		String val = "";
		if (props != null) {
			String prop = props.getProperty(key);
			if (prop != null) {
				val = prop;
			}
		}
		return val;
	}

}


配置用戶名以及密碼:mail-user.properties

 

 

#test
user.name = [email protected]
user.password = test_for_masque


郵件的主題和內容實體封裝

 

 

/**
 * 
 * @author [email protected]
 * 
 */
public class SimpleMail {

	private String subject;

	private String content;

	public String getSubject() {
		return subject;
	}

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

	public String getContent() {
		return content;
	}

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

}


郵件發送的類:

 

 

import java.util.List;
import java.util.Properties;

import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 簡單郵件發送器,可單發,羣發。
 * 
 * @author [email protected]
 * 
 */
public class SimpleMailSender {

	/**
	 * 發送郵件的props文件
	 */
	private final transient Properties props = System.getProperties();

	/**
	 * 郵件服務器登錄驗證
	 */
	private transient MailAuthenticator authenticator;

	/**
	 * 郵箱session
	 */
	private transient Session session;

	/**
	 * 初始化郵件發送器
	 * 
	 * @param smtpHostName
	 *            SMTP郵件服務器地址
	 * @param username
	 *            發送郵件的用戶名(地址)
	 * @param password
	 *            發送郵件的密碼
	 */
	public SimpleMailSender(final String smtpHostName, final String username,
			final String password) {
		init(username, password, smtpHostName);
	}

	/**
	 * 初始化郵件發送器
	 * 
	 * @param username
	 *            發送郵件的用戶名(地址),並以此解析SMTP服務器地址
	 * @param password
	 *            發送郵件的密碼
	 */
	public SimpleMailSender(final String username, final String password) {
		// 通過郵箱地址解析出smtp服務器,對大多數郵箱都管用
		final String smtpHostName = "smtp." + username.split("@")[1];
		init(username, password, smtpHostName);
	}

	/**
	 * 初始化
	 * 
	 * @param username
	 *            發送郵件的用戶名(地址)
	 * @param password
	 *            密碼
	 * @param smtpHostName
	 *            SMTP主機地址
	 */
	private void init(String username, String password, String smtpHostName) {
		// 初始化props
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.host", smtpHostName);
		// 驗證
		authenticator = new MailAuthenticator(username, password);
		// 創建session
		session = Session.getInstance(props, authenticator);
	}

	/**
	 * 發送郵件
	 * 
	 * @param recipient
	 *            收件人郵箱地址
	 * @param subject
	 *            郵件主題
	 * @param content
	 *            郵件內容
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public void send(String recipient, String subject, Object content)
			throws AddressException, MessagingException {
		// 創建mime類型郵件
		final MimeMessage message = new MimeMessage(session);
		// 設置發信人
		message.setFrom(new InternetAddress(authenticator.getUsername()));
		// 設置收件人
		message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
		// 設置主題
		message.setSubject(subject);
		// 設置郵件內容
		message.setContent(content.toString(), "text/html;charset=utf-8");
		// 發送
		Transport.send(message);
	}

	/**
	 * 羣發郵件
	 * 
	 * @param recipients
	 *            收件人們
	 * @param subject
	 *            主題
	 * @param content
	 *            內容
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public void send(List<String> recipients, String subject, Object content)
			throws AddressException, MessagingException {
		// 創建mime類型郵件
		final MimeMessage message = new MimeMessage(session);
		// 設置發信人
		message.setFrom(new InternetAddress(authenticator.getUsername()));
		// 設置收件人們
		final int num = recipients.size();
		InternetAddress[] addresses = new InternetAddress[num];
		for (int i = 0; i < num; i++) {
			addresses[i] = new InternetAddress(recipients.get(i));
		}
		message.setRecipients(RecipientType.TO, addresses);
		// 設置主題
		message.setSubject(subject);
		// 設置郵件內容
		message.setContent(content.toString(), "text/html;charset=utf-8");
		// 發送
		Transport.send(message);
	}

	/**
	 * 發送郵件
	 * 
	 * @param recipient
	 *            收件人郵箱地址
	 * @param mail
	 *            郵件對象
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public void send(String recipient, SimpleMail mail)
			throws AddressException, MessagingException {
		send(recipient, mail.getSubject(), mail.getContent());
	}

	/**
	 * 羣發郵件
	 * 
	 * @param recipients
	 *            收件人們
	 * @param mail
	 *            郵件對象
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public void send(List<String> recipients, SimpleMail mail)
			throws AddressException, MessagingException {
		send(recipients, mail.getSubject(), mail.getContent());
	}

}


運行測試主方法:將地址改爲自己的QQ郵箱測試下吧

 

 

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

/**
 * 
 * @author [email protected]
 * 
 */
public class Main {
	public static void main(String[] args) {
		try {
			SimpleMailSender sender = MailSenderFactory.getSender();
			List<String> recipients = new ArrayList<String>();
			for(int i=0;i<10;i++)
			recipients.add("[email protected]");
			for (String recipient : recipients)
				sender.send(recipient, "測試郵件", "這是一封測試郵件!");
			// sender.send(recipients, subject, content);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
}

 

 

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