一 便捷的MailSender和MailMessage
如果读者读了我的前面的两篇文章,相信对于JavaMail有了一定的认识。事实上,使用JavaMail API来发送邮件,并不是一件轻松的事情。幸运的是,Spring发挥了它一贯化繁为简的特点,对于JavaMail进行了“整容”,在降低开发者使用难度的同时,保留了JavaMail的强大功能。对于JavaMail邮件发送相关功能,Spring提供了一个抽象层,简化了操作。对于IavaMail邮件接收方面没有提供额外的功能。下面,重点来关注Spring时发送邮件的支持,在此不得不提的就是使用Spring编写邮件程序时需要掌握的两个最重要的内容:MailMessage和MaiISender。它们在org.springframework.mail包里,是代表邮件消息和邮件发送者的两个核心接口。
(1) MaiIMessage接口:提供各种便捷的方法允许用户快速设置邮件内容的各种属性信息。具体下表所示。
MaiIMessage接口的核心方法
方 法 名 | 方法描述 |
void setFrom(String from) | 设置发送地址 |
void setTo(String to) | 设置一个主送地址,如需设置多个地址,可以使用setTo(String[] to)方法 |
void setReplyTo(String replyTo) | 设置回复地址 |
void setCc(String cc) | 设置抄送地址,如需设置多个地址,可以使用setCc(String[] cc)方法 |
方 法 名 | 方法描述 |
void setBcc(String bcc) | 设置暗送地址,如需设置多个地址,可以使用setBcc(String[] bcc)方法 |
void setSentDate(Date sentDate) | 设置发送邮件的时间 |
void setSubject(String subject) | 设置邮件标题 |
void setText(String text) | 设置邮件内容 |
MaiIMessage接口定义的方法,功能类似于lavaMail的Message中的一些方法,但是看起来更简洁明了。在Spring中,MaiIMessage有两个实现类:SimpleMailMessage和MimeMaiIMessage。SimpleMaiIMessage主要用来实现简单的邮件消息,而对于较为复杂的MIME类型的邮件消息,需要JavaMail的MimeMessage的支持。lV[imeMa_ilMessage就是针对JavaMail MIME Message的MailMessage接口的实现类。在企业级应用中,我们通常会借助于MimeMessageHelper或者 MimeMessagePreparator来实现此类复杂邮件信息的发送。
(2) MaiISender接口:提供了发送简单邮件的策略,对于多数简单需求的邮件发送都可以通过它来实现。MailSender接口的方法比较简单,如下表所示。
表8-2 MaiISender接口的方法
方 法 名 | 方法描述 |
voidsend(SimDleMailMessage simpleMessage) | 发送一封简单信息的邮件 |
void send( SimpleMaiIMessage[ ] simpleMessages) | 一次性发送多封邮件 |
但是如果需要发送复杂的邮件,如MIME类型的邮件,需要使用MaiISender的子接口JavaMaiISender来实现。JavaMailSender提供了更多的方法支持,如表所示。
JavaMaiISender接口的方法
方 法 名 | 方法描述 |
MimeMessage createMimeMessage( ) | 相关的JavaMail Session创建一个新的MimeMessage对象 |
MimeMessage createMimeMessage(InputStream contentStream) | 使用给定的输入流作为消息来源,为Sender相关的JavaMail Session创建一 个新的MimeMessage对象 |
void send(MimeMessage mimeMessage) | 发送一封MIME类型的邮件 |
void send('MimeMessage[] mimeMessages) | 一次性发送多封MIME类型的邮件 |
void send (MimeMessagePreparator mimeMessagePreparator) | 通过特定的MimeMessagePreparator发送MIME类型的邮件 |
void send(MimeMessagePreparatorU mimeMessagePreparators) | 通过特定的一组MimeMessagePreparator发送MIME类型的邮件 |
案例开发环境:
邮件服务器: james2.3.2
jdk1.7
spring3.2.2
1. 建立java工程,导入相关jar包
2. 编写实体类
==============MailInfo.java============================
package com.obtk.entitys;
import java.io.File;
/**
* @author Administrator
*/
public class MailInfo {
//服务器(用域名表示wx.com 127.0.0.1)
private String mailServer;
private String mailSender; //邮件发送者
private String mailReceiver; //邮件接受者
private String mailSubject; //邮件标题
private String mailContent; //邮件内容
private String userName; //用户名
private String passWord; //密码
private String mailCc;//抄送地址
private String[] mailBcc; //抄送给很多人
private File[] attachments; //附件
public void setAttachments(File[] attachments) {
this.attachments = attachments;
}
public File[] getAttachments() {
return attachments;
}
public String getMailCc() {
return mailCc;
}
public void setMailCc(String mailCc) {
this.mailCc = mailCc;
}
public String[] getMailBcc() {
return mailBcc;
}
public void setMailBcc(String[] mailBcc) {
this.mailBcc = mailBcc;
}
public String getMailServer() {
return mailServer;
}
public void setMailServer(String mailServer) {
this.mailServer = mailServer;
}
public String getMailSender() {
return mailSender;
}
public void setMailSender(String mailSender) {
this.mailSender = mailSender;
}
public String getMailReceiver() {
return mailReceiver;
}
public void setMailReceiver(String mailReceiver) {
this.mailReceiver = mailReceiver;
}
public String getMailSubject() {
return mailSubject;
}
public void setMailSubject(String mailSubject) {
this.mailSubject = mailSubject;
}
public String getMailContent() {
return mailContent;
}
public void setMailContent(String mailContent) {
this.mailContent = mailContent;
}
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;
}
}
2. 编写业务类
=================MailBiz.java===================
package com.obtk.biz;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import com.obtk.entitys.MailInfo;
public class MailBiz {
private MailSender mailSender;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public void send(MailInfo mailInfo){
//强制类型转换
JavaMailSenderImpl sender=(JavaMailSenderImpl)mailSender;
//邮件信息
SimpleMailMessage msg=new SimpleMailMessage();
//发送者
msg.setFrom(sender.getUsername()+"@"+sender.getHost());
//接收者
msg.setTo(mailInfo.getMailReceiver());
//标题
msg.setSubject(mailInfo.getMailSubject());
//内容
msg.setText(mailInfo.getMailContent());
//抄送给谁
msg.setCc(mailInfo.getMailCc());
//发送
mailSender.send(msg);
}
}
3.编写配置文件
================ApplicationContext.xml======================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="wx.com"></property>
<property name="port" value="25"></property>
<property name="username" value="test1"></property>
<property name="password" value="123456"></property>
<property name="protocol" value="smtp"></property>
<property name="defaultEncoding" value="utf-8"></property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth"></prop>
</props>
</property>
</bean>
<bean id="mailBiz" class="com.obtk.biz.MailBiz">
<property name="mailSender" ref="mailSender"></property>
</bean>
</beans>
==================
4. 编写测试类
package com.obtk.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.obtk.biz.MailBiz;
import com.obtk.entitys.MailInfo;
public class TestSpring2 {
public static void main(String[] args) {
ApplicationContext context=
new ClassPathXmlApplicationContext("ApplicationContext.xml");
MailBiz mailBiz=(MailBiz)context.getBean("mailBiz");
MailInfo mailInfo=new MailInfo();
mailInfo.setMailReceiver("test2@wx.com");
mailInfo.setMailSubject("spring邮件发送");
mailInfo.setMailContent("hello,这是用spring发送邮件的内容");
mailInfo.setMailCc("test3@wx.com"); //抄送给一个人
mailBiz.send(mailInfo);
System.out.println("发送成功");
}
}
二 发送带附件的邮件
发送邮件的核心内容是Message,在前面小节中,发送的邮件内容都是纯文本,但在实际的企业级应用中,往往需要更复杂的邮件支持,如发送带附件的邮件。
例如:test1要给test2发送一封电子邮件,邮件内容需要附带两个.doc文件作为附件,分别为“test.doc”和“附件测试文件.doc”。效果如图所示。
对于复杂内容的电子邮件(如带附件的邮件、具有特殊编码的邮件、HTML类型的邮件等)需要使用JavaMail的MimeMessage。但是MimeMessage的使用比较复杂,因此,Spring提供了MimeMessageHelper类,对MimeMessage进行了封装,使开发者更简单地创建并填充MimeMessage。
具体代码:业务类MailAttachmentBiz.java
package com.obtk.biz;
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.obtk.entitys.MailInfo;
public class MailAttachmentBiz {
private JavaMailSender mailSender;
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void send(MailInfo mailInfo){
try {
//强制类型转换
JavaMailSenderImpl sender=(JavaMailSenderImpl)mailSender;
//邮件信息
MimeMessage msg=sender.createMimeMessage();
//附件发送者
MimeMessageHelper helper=new MimeMessageHelper(msg, true,"utf-8");
//发送者
helper.setFrom(sender.getUsername()+"@"+sender.getHost());
//接收者
helper.setTo(mailInfo.getMailReceiver());
//标题
helper.setSubject(mailInfo.getMailSubject());
//内容
helper.setText(mailInfo.getMailContent());
//抄送给谁
helper.setCc(mailInfo.getMailCc());
//添加附件
File[] files=mailInfo.getAttachments();
for(int i=0;i<files.length;i++){
helper.addAttachment(files[i].getName(), files[i]);
}
//发送
sender.send(msg);
} catch (MailException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="wx.com"></property>
<property name="port" value="25"></property>
<property name="username" value="test1"></property>
<property name="password" value="123456"></property>
<property name="protocol" value="smtp"></property>
<property name="defaultEncoding" value="utf-8"></property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth"></prop>
</props>
</property>
</bean>
<!-- 附件发送 -->
<bean id="attachmentMailBiz" class="com.obtk.biz.MailAttachmentBiz">
<property name="mailSender" ref="mailSender"></property>
</bean>
</beans>
测试类
package com.obtk.test;
import java.io.File;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.obtk.biz.MailAttachmentBiz;
import com.obtk.biz.MailBiz;
import com.obtk.entitys.MailInfo;
public class TestAttachmentMail {
public static void main(String[] args) {
ApplicationContext context=
new ClassPathXmlApplicationContext("ApplicationContext.xml");
MailAttachmentBiz mailBiz=(MailAttachmentBiz)context.getBean("attachmentMailBiz");
MailInfo mailInfo=new MailInfo();
mailInfo.setMailReceiver("test2@wx.com");
mailInfo.setMailSubject("spring邮件发送");
mailInfo.setMailContent("hello,这是用spring发送邮件的内容");
mailInfo.setMailCc("test3@wx.com"); //抄送给一个人
File[] files=new File[]{
new File("c:\\wx\\Apache_James_邮件服务器配置明细_final.doc"),
new File("c:\\wx\\spring邮件发送01.PNG")};
mailInfo.setAttachments(files);
mailBiz.send(mailInfo);
System.out.println("发送成功");
}
}
三 发送html格式邮件
在许多电子商务应用中,用户注册、购物成功、定时推送新商品信息等,多数是通过电子邮件
来告知用户的。如图所示,是京东购物网站在用户注册成功后发送的确认邮件。为了良好的用户体验,这封邮件以网页的形式进行呈现,看起来非常美观,同时也达到了营销产品的作用,吸引用户立刻进行网上购物。
具体代码:
业务类MailHtmlBiz.java
package com.obtk.biz;
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.obtk.entitys.MailInfo;
public class MailHtmlBiz {
private JavaMailSender mailSender;
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void send(MailInfo mailInfo){
try {
//强制类型转换
JavaMailSenderImpl sender=(JavaMailSenderImpl)mailSender;
//邮件信息
MimeMessage msg=sender.createMimeMessage();
//附件发送者
MimeMessageHelper helper=new MimeMessageHelper(msg, true,"utf-8");
//发送者
helper.setFrom(sender.getUsername()+"@"+sender.getHost());
//接收者
helper.setTo(mailInfo.getMailReceiver());
//标题
helper.setSubject(mailInfo.getMailSubject());
//true参数表示发送html文本
helper.setText(mailInfo.getMailContent(),true);
//抄送给谁
helper.setCc(mailInfo.getMailCc());
//添加附件
File[] files=mailInfo.getAttachments();
for(int i=0;i<files.length;i++){
helper.addAttachment(files[i].getName(), files[i]);
}
//发送
sender.send(msg);
} catch (MailException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
配置
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="wx.com"></property>
<property name="port" value="25"></property>
<property name="username" value="test1"></property>
<property name="password" value="123456"></property>
<property name="protocol" value="smtp"></property>
<property name="defaultEncoding" value="utf-8"></property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth"></prop>
</props>
</property>
</bean>
<!-- html发送 -->
<bean id="htmlMailBiz" class="com.obtk.biz.MailHtmlBiz">
<property name="mailSender" ref="mailSender"></property>
</bean>
测试类
package com.obtk.test;
import java.io.File;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.obtk.biz.MailAttachmentBiz;
import com.obtk.biz.MailBiz;
import com.obtk.biz.MailHtmlBiz;
import com.obtk.entitys.MailInfo;
public class TestHtmlMail {
public static void main(String[] args) {
ApplicationContext context=
new ClassPathXmlApplicationContext("ApplicationContext.xml");
MailHtmlBiz mailBiz=(MailHtmlBiz)context.getBean("htmlMailBiz");
MailInfo mailInfo=new MailInfo();
mailInfo.setMailReceiver("test2@wx.com");
mailInfo.setMailSubject("spring邮件发送");
mailInfo.setMailCc("test3@wx.com"); //抄送给一个人
File[] files=new File[]{
new File("c:\\wx\\Apache_James_邮件服务器配置明细_final.doc"),
new File("c:\\wx\\spring邮件发送01.PNG")};
mailInfo.setAttachments(files);
//发送内容
StringBuffer sbf=new StringBuffer();
sbf.append("<html>\r\n");
sbf.append("<head>\r\n");
sbf.append("<meta http-equiv='Content-Type' content='text/html;charset=utf-8' />\r\n");
sbf.append("<title>无标题文档</title>\r\n");
sbf.append("</head>\r\n");
sbf.append("<body>\r\n");
sbf.append("<h2>展示狗狗的数据</h2>\r\n");
sbf.append("<table border='1px'>\r\n");
sbf.append("<tr><td>狗狗编号</td><td>名称</td><td>类别</td></tr>\r\n");
for(int i=0;i<5;i++){
sbf.append("<tr><td>dog"+i+"</td>");
sbf.append(" <td>旺财"+i+"</td>");
sbf.append(" <td>土狗"+i+"</td></tr>\r\n");
}
sbf.append("</table>\r\n");
sbf.append("</body>\r\n");
sbf.append("</html>\r\n");
mailInfo.setMailContent(sbf.toString());
mailBiz.send(mailInfo);
System.out.println("发送成功");
}
}
四 用模板发送邮件
在有些HTML格式的邮件中,大部分的HTML代码都是固定的,只有少部分可能是变化的,如邮件中涉及的用户信息等。强大的模板技术最适合解决类似问题。使用模板技术会让开发变得简单,而且可将邮件的展现形式和业务逻辑分离开来,改变展现形式就不需要改代码了。FreeMarker是一款模板引擎,即一种基于模板、用来生成输出文本的通用工具。可以通过访问官方网站(http://freemarker.org)下载freemarker.jar的2.3版本。
FreeMarker使用模板文件来代替静态的HTML文本。模板文件同样是静态的HTML代码,但是除了这些HTML代码外,代码中还包括了一些FreeMarker指令元素,而这些指令元素就能够做到动态地生成部分内容。先导入freemaker的jar包
然后编写模板文件
模板文件重新打开有可能会有中文乱码,在文件上单击右键可以解决。
编写业务类
package com.obtk.biz;
import java.io.File;
import java.util.HashMap;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import com.obtk.entitys.MailInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class MailTemplateBiz {
private JavaMailSender mailSender;
private Configuration config;
public void setConfig(Configuration config) {
this.config = config;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void send(MailInfo mailInfo){
try {
//强制类型转换
JavaMailSenderImpl sender=(JavaMailSenderImpl)mailSender;
//邮件信息
MimeMessage msg=sender.createMimeMessage();
//附件发送者
MimeMessageHelper helper=new MimeMessageHelper(msg, true,"utf-8");
//发送者
helper.setFrom(sender.getUsername()+"@"+sender.getHost());
//接收者
helper.setTo(mailInfo.getMailReceiver());
//标题
helper.setSubject(mailInfo.getMailSubject());
//用模板发送
//取到模板实例
Template template=config.getTemplate("mail.ftl");
//向模板中传递参数
HashMap<String, String> paramMap=new HashMap<String, String>();
paramMap.put("userName", "麻子");
String theContent=FreeMarkerTemplateUtils.processTemplateIntoString(template, paramMap);
//内容
helper.setText(theContent,true);
//抄送给谁
helper.setCc(mailInfo.getMailCc());
//添加附件
File[] files=mailInfo.getAttachments();
for(int i=0;i<files.length;i++){
helper.addAttachment(files[i].getName(), files[i]);
}
//发送
sender.send(msg);
} catch (MailException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
配置:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="wx.com"></property>
<property name="port" value="25"></property>
<property name="username" value="test1"></property>
<property name="password" value="123456"></property>
<property name="protocol" value="smtp"></property>
<property name="defaultEncoding" value="utf-8"></property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth"></prop>
</props>
</property>
</bean>
<!-- 模板发送 -->
<bean id="config" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
<!-- 指明模板的位置 -->
<property name="templateLoaderPath" value="com/obtk/entitys/"></property>
<property name="freemarkerSettings">
<props>
<prop key="default_encoding">gbk</prop>
</props>
</property>
</bean>
<bean id="tempLateMailBiz" class="com.obtk.biz.MailTemplateBiz">
<property name="mailSender" ref="mailSender"></property>
<property name="config" ref="config"></property>
</bean>
测试类
package com.obtk.test;
import java.io.File;
import java.util.HashMap;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.obtk.biz.MailAttachmentBiz;
import com.obtk.biz.MailBiz;
import com.obtk.biz.MailTemplateBiz;
import com.obtk.entitys.MailInfo;
import freemarker.template.Template;
public class TestTemplateMail {
public static void main(String[] args) {
ApplicationContext context=
new ClassPathXmlApplicationContext("ApplicationContext.xml");
MailTemplateBiz mailBiz=(MailTemplateBiz)context.getBean("tempLateMailBiz");
MailInfo mailInfo=new MailInfo();
mailInfo.setMailReceiver("test2@wx.com");
mailInfo.setMailSubject("spring邮件发送");
mailInfo.setMailCc("test3@wx.com"); //抄送给一个人
File[] files=new File[]{
new File("c:\\wx\\Apache_James_邮件服务器配置明细_final.doc"),
new File("c:\\wx\\spring邮件发送01.PNG")};
mailInfo.setAttachments(files);
mailBiz.send(mailInfo);
System.out.println("发送成功");
}
}