java发送邮件,Authenticator,Session,Message,Multipart,BodyPart

使用java实现发送邮件功能,主要用到了Authenticator,Session,Message,Multipart,BodyPart。

Authenticator:抽象类,继承该类要实现getPasswordAuthentication方法,该方法主要是获取邮箱账户密码,用于用户验证。

Session:根据Properties属性,和用户验证信息创建MimeMessage;

Message:即MimeMessage,用户填写邮件的一些信息,如发送者,接收者,主题,内容,附件等;

Multipart:容器类,用于装作封装了邮件正文内容和附件的BodyPart;

BodyPart:封装邮件正文和附件及编写附件名称,有一点需要注意,如果邮件中有附件,一定要先添加附件后添加邮件正文,如果顺序颠倒,你编写的邮件正文内容会被附件覆盖掉;

以下为正式代码:

package cn.tongmap.global;

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

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

public class Mail extends Authenticator{
	//账号
	private static String ACCOUNT_NUMBER;
	//密码
	private static String SECURITY_CODE;
	//邮箱主机
	private static String MAIL_SMTP_HOST;
	//邮箱端口
	private static int MAIL_SMTP_PORT;
	//是否验证
	private static boolean MAIL_SMTP_AUTH;
	
	static {
		Properties pro = null;
		try {
			pro = new Properties();
			pro.load(Mail.class.getResourceAsStream("/mail.properties"));
			//人流量数据SFTP服务器信息
			ACCOUNT_NUMBER = pro.getProperty("ACCOUNT_NUMBER").trim();
			SECURITY_CODE = pro.getProperty("SECURITY_CODE").trim();
			MAIL_SMTP_HOST = pro.getProperty("MAIL_SMTP_HOST").trim();
			MAIL_SMTP_PORT = Integer.parseInt(pro.getProperty("MAIL_SMTP_PORT").trim());
			MAIL_SMTP_AUTH = Boolean.parseBoolean(pro.getProperty("MAIL_SMTP_AUTH").trim());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//邮件主题
	private String subject;
	//邮件内容,可以使用html
	private String content;
	//附件源
	private String fileDataSource;
	//邮件接收者
	private List<String> recipients;
	
	public Mail() {
	}

	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;
	}

	public String getFileDataSource() {
		return fileDataSource;
	}

	public void setFileDataSource(String fileDataSource) {
		this.fileDataSource = fileDataSource;
	}

	public List<String> getRecipients() {
		return recipients;
	}

	public void setRecipients(List<String> recipients) {
		this.recipients = recipients;
	}
	/**
	 * 此方法一定要实现,否侧会连接出错,因为要进行用户名密码验证
	 */
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(ACCOUNT_NUMBER, SECURITY_CODE);
	}

	/**
	 * 邮件发送,在实例化对象的时候会需要填写一些发送邮件必要参数
	 * 在发送邮件时不需要任何参数
	 * @return 返回内容为字符串,用于提示邮件发送结果或错误提示
	 * @throws Exception
	 */
	public String send() throws Exception {
		if(null == recipients || recipients.size() == 0) {
			return "请填写邮件接收者!";
		}
		if(null == subject || "".equals(subject)) {
			return "请填写邮寄主题!";
		}
		if(null == content || "".equals(content)) {
			return "请填写邮寄内容!";
		}
		Authenticator auth = new Mail();
		Properties pro = new Properties();
		pro.put("mail.smtp.host", MAIL_SMTP_HOST);
		pro.put("mail.smtp.port", MAIL_SMTP_PORT);
		pro.put("mail.smtp.auth", MAIL_SMTP_AUTH);
		Session sendMailSession = Session.getDefaultInstance(pro, auth);
		// 根据session创建一个邮件消息
		Message mailMessage = new MimeMessage(sendMailSession);
		// 创建邮件发送者地址
		Address from = new InternetAddress(ACCOUNT_NUMBER);
		// 设置邮件消息的发送者
		mailMessage.setFrom(from);
		// 创建邮件的接收者地址,并设置到邮件消息中
		Address[] tos = new Address[recipients.size()];
		for (int i = 0; i < tos.length; i++) {
			tos[i] = new InternetAddress(recipients.get(i));
		}
		// Message.RecipientType.TO属性表示接收者的类型为TO
		mailMessage.setRecipients(Message.RecipientType.TO, tos);
		// 设置邮件消息的主题
		mailMessage.setSubject(subject);
		// 设置邮件消息发送的时间
		mailMessage.setSentDate(new Date());
		// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
		Multipart mainPart = new MimeMultipart();
		// 创建一个包含HTML内容的MimeBodyPart
		BodyPart html = new MimeBodyPart();
		//是否存在附件
		if(null != fileDataSource && !"".equals(fileDataSource)) {
			File file = new File(fileDataSource);
			if(file.exists()) {
				FileDataSource data = new FileDataSource(file);
				html.setDataHandler(new DataHandler(data));
				//避免文件名中文乱码
				String name = MimeUtility.encodeWord(file.getName());
				html.setFileName(name);
			} else {
				return "邮件中存在无效附件!";
			}
		}
		// 设置HTML内容,设置内容步骤要放在设置附件之后,以免内容被覆盖
		html.setContent(content, "text/html; charset=utf-8");
		mainPart.addBodyPart(html);
		// 将MiniMultipart对象设置为邮件内容
		mailMessage.setContent(mainPart);
		// 发送邮件
		Transport.send(mailMessage);
		return "邮件发送成功!";
	}
}

 其中mail.properties为邮件配置文件,单独放出来便于管理:

ACCOUNT_NUMBER = You [email protected]
SECURITY_CODE = You Email Password
MAIL_SMTP_HOST = smtp.163.com
MAIL_SMTP_PORT = 25
MAIL_SMTP_AUTH =true

 

你可能感兴趣的:(java发送邮件,transport,MimeMessage,MimeMultipart,MimeBodyPart)