Java郵件開發簡單例子

Java郵件開發簡單例子,代碼源自傳智播客巴巴運動網,已經把這個小Demo項目放在個人的資源裏了!這裏使用的是163郵箱服務器!

package com.wxc.util.email;

import java.io.File;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
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;

import com.wxc.util.PropertyReadUtil;

/**
 * 
 * 郵件工具類
 * 
 * @author wuxincheng
 * 
 */
public class EmailSenderUtil {

	private static final String charset = "UTF-8";
	private static final String defaultMimetype = "text/plain";
	
	// 這是讀取配置文件工具類, 用來讀取Email用戶名和密碼
	private static final PropertyReadUtil param = new PropertyReadUtil(
			"parameters");

	public static void main(String[] args) {
		PropertyReadUtil param = new PropertyReadUtil("parameters");
		
		String[] emails = param.getString("receiver.email.address").split(",");
		
		EmailSenderUtil.send(emails, "Java郵件測試", "<b>CSDN分享資源</b>", null , "text/html");
		
	}

	/**
	 * 發送郵件
	 * 
	 * @param receiver
	 *            收件人
	 * @param subject
	 *            標題
	 * @param mailContent
	 *            郵件內容
	 * @param mimetype
	 *            內容類型 默認爲text/plain,如果要發送HTML內容,應設置爲text/html
	 */
	public static void send(String receiver, String subject,
			String mailContent, String mimetype) {
		send(new String[] { receiver }, subject, mailContent, mimetype);
	}

	/**
	 * 發送郵件
	 * 
	 * @param receivers
	 *            收件人
	 * @param subject
	 *            標題
	 * @param mailContent
	 *            郵件內容
	 * @param mimetype
	 *            內容類型 默認爲text/plain,如果要發送HTML內容,應設置爲text/html
	 */
	public static void send(String[] receivers, String subject,
			String mailContent, String mimetype) {
		send(receivers, subject, mailContent, null, mimetype);
	}

	/**
	 * 發送郵件
	 * 
	 * @param receivers
	 *            收件人
	 * @param subject
	 *            標題
	 * @param mailContent
	 *            郵件內容
	 * @param attachements
	 *            附件
	 * @param mimetype
	 *            內容類型 默認爲text/plain,如果要發送HTML內容,應設置爲text/html
	 */
	public static void send(String[] receivers, String subject,
			String mailContent, File[] attachements, String mimetype) {
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.163.com"); // smtp服務器地址 sohu
		props.put("mail.smtp.auth", "true"); // 需要校驗
		Session session = Session.getDefaultInstance(props,
				new Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(param
								.getString("sender.email.address"), param
								.getString("sender.email.password")); // 登錄用戶名/密碼
					}
				});

		session.setDebug(true);

		try {
			MimeMessage mimeMessage = new MimeMessage(session);
			mimeMessage.setFrom(new InternetAddress(param
					.getString("sender.email.address"))); // 發件人郵件

			InternetAddress[] toAddress = new InternetAddress[receivers.length];
			for (int i = 0; i < receivers.length; i++) {
				toAddress[i] = new InternetAddress(receivers[i]);
			}
			mimeMessage.setRecipients(Message.RecipientType.TO, toAddress); // 收件人郵件
			mimeMessage.setSubject(subject, charset);

			Multipart multipart = new MimeMultipart();
			// 正文
			MimeBodyPart body = new MimeBodyPart();
			// body.setText(message, charset);不支持html
			body.setContent(mailContent,
					(mimetype != null && !"".equals(mimetype) ? mimetype
							: defaultMimetype) + ";charset=" + charset);
			multipart.addBodyPart(body); // 發件內容
			// 附件
			if (attachements != null) {
				for (File attachement : attachements) {
					MimeBodyPart attache = new MimeBodyPart();
					// ByteArrayDataSource bads = new
					// ByteArrayDataSource(byte[],"application/x-any");
					attache.setDataHandler(new DataHandler(new FileDataSource(
							attachement)));
					String fileName = getLastName(attachement.getName());
					attache.setFileName(MimeUtility.encodeText(fileName,
							charset, null));
					multipart.addBodyPart(attache);
				}
			}
			mimeMessage.setContent(multipart);
			// SimpleDateFormat formcat = new SimpleDateFormat("yyyy-MM-dd");
			mimeMessage.setSentDate(new Date()); // formcat.parse("2010-5-23")
			Transport.send(mimeMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String getLastName(String fileName) {
		int pos = fileName.lastIndexOf("\\");
		if (pos > -1) {
			fileName = fileName.substring(pos + 1);
		}
		pos = fileName.lastIndexOf("/");
		if (pos > -1) {
			fileName = fileName.substring(pos + 1);
		}
		return fileName;
	}

}



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