Java Mail封装

本教程教会你如何基于java mail封装自己的邮件发送工具集合。本文章会提到并和Spring提供的邮件发送工具类相比,并构建常用功能的邮件发送类库。


对于java mail的基础,请参考该链接文章:http://www.yiibai.com/javamail_api/


Spring已经给我们提供了一个java mail的封装类org.springframework.mail.javamail.JavaMailSender。但是由于Spring灵活和自定义的方式,使得发送邮件也还是需要构建不少代码,甚至是基于原始的java mail构建其邮件体(实现其接口),然后再调用相应的发送方法去发送。

  • Spring发送邮件的代码如下:

package com.sparrowcode.common.module.mail;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;

public class SpringMailSender {

	// #ST fileds
	private JavaMailSender javaMailSender;
	private String from;

	// #ED fileds

	// #ST properties
	public JavaMailSender getJavaMailSender() {
		return javaMailSender;
	}

	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	// #ED properties

	// #ST methods
	public void sendSimpleMail(String to, String subject, String text) {
		SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
		simpleMailMessage.setFrom(from);
		simpleMailMessage.setTo(to);
		simpleMailMessage.setSubject(subject);
		simpleMailMessage.setText(text);
		javaMailSender.send(simpleMailMessage);
	}

	public void sendComplicatedMail(final String to, final String subject, final String text) throws MessagingException {
		javaMailSender.send(new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper mmh = new MimeMessageHelper(mimeMessage, true);
				// 发送人,收件人,主题,内容
				mmh.setFrom(from);
				mmh.setTo(to);
				mmh.setSubject(subject);
				mmh.setText(text, true);
			}
		});
	}

	// #ED methods

}

  • Spring配置如下:

<!-- SpringMail -->
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	<property name="defaultEncoding" value="UTF-8" />
	<property name="host" value="smtp.qq.com" />
	<property name="username" value="sparrowcaode@163.com" />
	<property name="password" value="123456" />
	<property name="javaMailProperties">
		<props>
			<prop key="mail.smtp.auth">true</prop>
			<prop key="mail.debug">true</prop>
			<prop key="mail.smtp.timeout">25000</prop>
			<prop key="mail.smtp.port">25</prop>
		</props>
	</property>
</bean>
<bean id="springMailSender" class="com.sparrowcode.common.module.mail.SpringMailSender">
	<property name="javaMailSender" ref="javaMailSender" />
	<property name="from">
		<value><![CDATA[lalahu<1234567890@qq.com>]]></value>
	</property>
</bean>
  • Demo
package com.sparrowcode.common.module.mail;

import javax.mail.MessagingException;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringMailTest {

	@Test
	public void simpleTest() {
		ApplicationContext actx = new ClassPathXmlApplicationContext("spring-mail.xml");
		SpringMailSender mailProvider = (SpringMailSender) actx.getBean("springMailSender");

		mailProvider.sendSimpleMail("hws_work@163.com", "spring简单测试", "测试邮件.......");
	}

	@Test
	public void complicatedTest() throws MessagingException {
		ApplicationContext actx = new ClassPathXmlApplicationContext("spring-mail.xml");
		SpringMailSender mailProvider = (SpringMailSender) actx.getBean("springMailSender");

		mailProvider.sendComplicatedMail("hws_work@163.com", "spring简单测试",
				"<a href='http://www.baidu.com'>测试邮件.......</a><img src='http://img4.imgtn.bdimg.com/it/u=484801982,762919538&fm=21&gp=0.jpg' />");
	}
}


自己动手封装常用功能的邮件发送工具集合:

  • 构建认证类,用于身份认证:
package com.sparrowcode.common.module.mail;

import javax.mail.*;

public class MailAuthenticator extends Authenticator {

	String userName = null;
	String password = null;

	public MailAuthenticator() {
	}

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

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(userName, password);
	}
}
  • 构建消息邮件体对象,存储用于构建java mail邮件体的基本信息。包含常用的字段:来源、目的地、抄送、密送、标题、内容、附件列表、嵌套图片列表:
package com.sparrowcode.common.module.mail;

import java.util.ArrayList;
import java.util.List;

public class MailMessage {

	// #ST fields
	private String from;
	private List<String> to = new ArrayList<String>();
	private List<String> cc = new ArrayList<String>();
	private List<String> bcc = new ArrayList<String>();
	private String subject;
	private String content;
	private List<String> attachFileNames = new ArrayList<String>();
	private List<String> imageFileNames = new ArrayList<String>();

	// #ED fields

	// #ST properties
	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public List<String> getTo() {
		return to;
	}

	public void setTo(List<String> to) {
		if (to != null) {
			this.to = to;
		}
	}

	public List<String> getCc() {
		return cc;
	}

	public void setCc(List<String> cc) {
		if (cc != null) {
			this.cc = cc;
		}
	}

	public List<String> getBcc() {
		return bcc;
	}

	public void setBcc(List<String> bcc) {
		if (bcc != null) {
			this.bcc = bcc;
		}
	}

	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 List<String> getAttachFileNames() {
		return attachFileNames;
	}

	public void setAttachFileNames(List<String> attachFileNames) {
		if (attachFileNames != null) {
			this.attachFileNames = attachFileNames;
		}
	}

	public List<String> getImageFileNames() {
		return imageFileNames;
	}

	public void setImageFileNames(List<String> imageFileNames) {
		if (imageFileNames != null) {
			this.imageFileNames = imageFileNames;
		}
	}

	// #ED properties

	// #ST constructor
	public MailMessage() {
		super();
	}

	public MailMessage(String from, String to, String cc, String bcc, String subject, String content) {
		super();
		if (from != null)
			this.from = from;
		if (to != null)
			this.to.add(to);
		if (cc != null)
			this.cc.add(cc);
		if (bcc != null)
			this.bcc.add(bcc);
		if (subject != null)
			this.subject = subject;
		if (content != null)
			this.content = content;
	}

	// #ED constructor

	// #ST methods
	public void addTo(String to) {
		this.to.add(to);
	}

	public void addAttachFileName(String fullName) {
		this.attachFileNames.add(fullName);
	}

	// #ED methods

}
  • 构建发送对象,考虑和SpringMail的配置兼容,所以构建字段主要注意一下。在发送前,先将邮件体相关信息转换成java mail的消息体,然后再发送出去。发送内部转换封装好的数据的好处是,对于任何方式的发送方法,均提供统一的一个数据结构和简单的发送接口即可实现相应的邮件发送功能:
package com.sparrowcode.common.module.mail;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

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

import com.sparrowcode.common.lang.lang.FileUtil;

public class MailSender {

	// #ST fields
	// user's name and password
	private String username;
	private String password;
	// other settings
	private String defaultEncoding = "UTF-8";
	private Properties javaMailProperties;

	// #ED fields

	// #ST properties

	public String getUsername() {
		return username;
	}

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

	public String getPassword() {
		return password;
	}

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

	public String getDefaultEncoding() {
		return defaultEncoding;
	}

	public void setDefaultEncoding(String defaultEncoding) {
		this.defaultEncoding = defaultEncoding;
	}

	public Properties getJavaMailProperties() {
		return javaMailProperties;
	}

	public void setJavaMailProperties(Properties javaMailProperties) {
		this.javaMailProperties = javaMailProperties;
	}

	// #ED properties

	// #ST public methods

	public void sendText(MailMessage mailMessage) throws MessagingException, UnsupportedEncodingException {
		// create authenticator an session
		MailAuthenticator authenticator = new MailAuthenticator(this.username, this.password);
		Session session = Session.getDefaultInstance(javaMailProperties, authenticator);
		// according to the session, create a email model(MimeMessage), then set
		// email information about the address part .
		Message message = new MimeMessage(session);
		addDestinations(message, mailMessage);
		// set mail information and content.
		addContent(message, mailMessage, false);
		// send
		Transport.send(message);
	}

	public void sendHtml(MailMessage mailMessage) throws MessagingException, UnsupportedEncodingException {
		// create authenticator an session
		MailAuthenticator authenticator = new MailAuthenticator(this.username, this.password);
		Session session = Session.getDefaultInstance(this.javaMailProperties, authenticator);
		// according to the session, create a email model, then set email
		// information.
		Message message = new MimeMessage(session);
		addDestinations(message, mailMessage);
		// set mail information and content.
		addContent(message, mailMessage, true);
		// send email.
		Transport.send(message);
	}

	// TODO 有问题,需修改
	public void sendHtmlImage(MailMessage mailMessage) throws MessagingException, UnsupportedEncodingException {
		// create authenticator an session
		MailAuthenticator authenticator = new MailAuthenticator(this.username, this.password);
		Session session = Session.getDefaultInstance(this.javaMailProperties, authenticator);
		// according to the session, create a email model, then set email
		// information.
		Message message = new MimeMessage(session);
		addDestinations(message, mailMessage);

		Multipart multipart = new MimeMultipart("related");

		// first part (the html)
		BodyPart messageBodyPart = new MimeBodyPart();
		String htmlText = "<H1>Hello</H1>11111<img src=\"cid:image\">";
		messageBodyPart.setContent(htmlText, "text/html;charset=UTF-8");
		// add it
		multipart.addBodyPart(messageBodyPart);

		// second part (the image)
		messageBodyPart = new MimeBodyPart();
		DataSource fds = new FileDataSource("C:/Users/Administrator/Desktop/1.png");
		messageBodyPart.setDataHandler(new DataHandler(fds));
		messageBodyPart.setHeader("Content-ID", "image");

		// add image to the multipart
		multipart.addBodyPart(messageBodyPart);

		// put everything together
		// set mail information and content.
		message.setSubject(mailMessage.getSubject());
		message.setSentDate(new Date());
		message.setContent(multipart);

		// send email
		Transport.send(message);
	}

	public void sendHtmlAttach(MailMessage mailMessage) throws MessagingException, UnsupportedEncodingException {
		// create authenticator an session
		MailAuthenticator authenticator = new MailAuthenticator(this.username, this.password);
		Session session = Session.getDefaultInstance(this.javaMailProperties, authenticator);
		// according to the session, create a email model, then set email
		// information.
		Message message = new MimeMessage(session);
		addDestinations(message, mailMessage);
		// create email carrier, including the part of html and the part of
		// attachments.
		Multipart multipart = new MimeMultipart();
		// create the part of html,then add it to the Multipart.
		BodyPart htmlPart = new MimeBodyPart();
		htmlPart.setContent(mailMessage.getContent(), "text/html; charset=" + this.defaultEncoding);
		multipart.addBodyPart(htmlPart);
		// the part of attachment
		addAttachments(multipart, mailMessage.getAttachFileNames());
		// set mail content.
		message.setSubject(mailMessage.getSubject());
		message.setSentDate(new Date());
		message.setContent(multipart);
		// send email.
		Transport.send(message);
	}

	// #ED public methods

	// #ST private methods
	private void addContent(Message message, MailMessage mailMessage, boolean isHtml) throws MessagingException {
		message.setSubject(mailMessage.getSubject());
		message.setSentDate(new Date());
		if (isHtml) {
			message.setContent(mailMessage.getContent(), "text/html; charset=" + this.defaultEncoding);
		} else {
			message.setText(mailMessage.getContent());
		}
	}

	private void addDestinations(Message message, MailMessage mailMessage) throws MessagingException, UnsupportedEncodingException {
		// set sender address and name.
		Address from = new InternetAddress(mailMessage.getFrom());
		((InternetAddress) from).setPersonal(((InternetAddress) from).getPersonal(), "UTF-8");
		message.setFrom(from);
		// set destinations, including to,cc,bcc.
		addAddress(message, Message.RecipientType.TO, mailMessage.getTo());
		addAddress(message, Message.RecipientType.CC, mailMessage.getCc());
		addAddress(message, Message.RecipientType.BCC, mailMessage.getBcc());
	}

	private void addAddress(Message message, RecipientType type, List<String> addresses) throws MessagingException {
		Address[] adds = new Address[addresses.size()];
		for (int i = 0; i < addresses.size(); i++) {
			Address add = new InternetAddress(addresses.get(i));
			adds[i] = add;
		}
		message.setRecipients(type, adds);
	}

	private void addAttachments(Multipart multipart, List<String> attachFileNames) throws MessagingException, UnsupportedEncodingException {
		for (int i = 0; i < attachFileNames.size(); i++) {
			BodyPart attachmentPart = new MimeBodyPart();
			String filename = attachFileNames.get(i);
			String shortName = FileUtil.getShortName(filename);
			DataSource source = new FileDataSource(filename);
			attachmentPart.setDataHandler(new DataHandler(source));
			attachmentPart.setFileName(MimeUtility.encodeText(shortName));
			multipart.addBodyPart(attachmentPart);
		}
	}
	// #ED private methods
}
  • Spring配置文件配置(和SpringMail的配置一样的,实际上,我们只需要替换一下实现类即可):
<!-- SparrowMail -->
	<bean id="mailMessage" class="com.sparrowcode.common.module.mail.MailMessage">
		<property name="from">
			<value><![CDATA[拉拉湖<497721267@qq.com>]]></value>
		</property>
	</bean>
	<bean id="mailSender" class="com.sparrowcode.common.module.mail.MailSender" scope="singleton">
		<property name="defaultEncoding" value="UTF-8" />
		<property name="username" value="497721267@qq.com" />
		<property name="password" value="111111111" />
		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">true</prop>
				<prop key="mail.debug">true</prop>
				<prop key="mail.smtp.timeout">25000</prop>
				<prop key="mail.smtp.host">smtp.qq.com</prop>
				<prop key="mail.smtp.port">25</prop>
			</props>
		</property>
	</bean>
  • Demo:
package com.sparrowcode.common.module.mail;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.MessagingException;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SparrowMailTest {

	// ************************自定义封装方式API方式
	@Test
	public void sendText() throws UnsupportedEncodingException, MessagingException {

		MailMessage mailMessage = new MailMessage("lalahu<497721267@qq.com>", "hws_work@163.com", null, "497721267@qq.com", "测试数据", "测试数据数据数据、。。。。");
		
		MailSender mailSender = new MailSender();
		
		Properties javaMailProperties = new Properties();
		javaMailProperties.put("mail.smtp.auth", "true");
		javaMailProperties.put("mail.smtp.starttls.enable", "true");
		javaMailProperties.put("mail.smtp.host", "smtp.qq.com");
		javaMailProperties.put("mail.smtp.port", "25");
		javaMailProperties.put("mail.debug", "true");

		mailSender.setJavaMailProperties(javaMailProperties);
		mailSender.setUsername("497721267@qq.com");
		mailSender.setPassword("vinsonhu19911109");

		mailSender.sendText(mailMessage);
	}

	@Test
	public void sendHtml() throws MessagingException, UnsupportedEncodingException {

		MailMessage mailMessage = new MailMessage("lalahu<497721267@qq.com>", "hws_work@163.com", null, "497721267@qq.com", "测试数据", "<a href='http://www.baidu.com'>测试数据数据数据</a>。。。。");

		MailSender mailSender = new MailSender();

		Properties javaMailProperties = new Properties();
		javaMailProperties.put("mail.smtp.auth", "true");
		javaMailProperties.put("mail.smtp.starttls.enable", "true");
		javaMailProperties.put("mail.smtp.host", "smtp.qq.com");
		javaMailProperties.put("mail.smtp.port", "25");
		javaMailProperties.put("mail.debug", "true");

		mailSender.setJavaMailProperties(javaMailProperties);
		mailSender.setUsername("497721267@qq.com");
		mailSender.setPassword("111111");
		mailSender.sendHtml(mailMessage);
	}

	@Test
	public void sendHtmlImage() throws MessagingException {
		MailSender mailSender = new MailSender();

		Properties javaMailProperties = new Properties();
		javaMailProperties.put("mail.smtp.auth", "true");
		javaMailProperties.put("mail.smtp.starttls.enable", "true");
		javaMailProperties.put("mail.smtp.host", "smtp.qq.com");
		javaMailProperties.put("mail.smtp.port", "25");
		javaMailProperties.put("mail.debug", "true");

		mailSender.setJavaMailProperties(javaMailProperties);
		mailSender.setUsername("497721267@qq.com");
		mailSender.setPassword("111111");

		// mailSender.sendHtmlImage();
	}

	@Test
	public void SendHtmlAttachment() throws MessagingException, UnsupportedEncodingException {
		MailMessage mailMessage = new MailMessage("lalahu<497721267@qq.com>", "hws_work@163.com", null, "497721267@qq.com", "测试数据",
				"<a href='http://www.baidu.com'>测试数据数据数据</a>。。。。");
		mailMessage.addAttachFileName("C:\\Users\\Zero\\Desktop\\HWS_Frame_Spring.docx");

		MailSender mailSender = new MailSender();

		Properties javaMailProperties = new Properties();
		javaMailProperties.put("mail.smtp.auth", "true");
		javaMailProperties.put("mail.smtp.starttls.enable", "true");
		javaMailProperties.put("mail.smtp.host", "smtp.qq.com");
		javaMailProperties.put("mail.smtp.port", "25");
		javaMailProperties.put("mail.debug", "true");

		mailSender.setJavaMailProperties(javaMailProperties);
		mailSender.setUsername("497721267@qq.com");
		mailSender.setPassword("111111");

		mailSender.sendHtmlAttach(mailMessage);
	}

	// ************************自定义封装Spring管理方式
	@Test
	public void SpringSendText() throws MessagingException, UnsupportedEncodingException {
		ApplicationContext actx = new ClassPathXmlApplicationContext("spring-mail.xml");
		MailSender mailSender = (MailSender) actx.getBean("mailSender");
		MailMessage mailMessage = (MailMessage) actx.getBean("mailMessage");

		mailMessage.addTo("hws_work@163.com");
		mailMessage.setSubject("spring封装测试");
		mailMessage.setContent("spring封装测试邮件。。。");

		mailSender.sendHtml(mailMessage);

	}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值