参考资料
1 Spring邮件发送(可带附件,模板,群发,异步发送等功能)
http://linqincai.iteye.com/blog/508797
2 Spring mail 使用多个账号发送带有附件的HTML邮件
http://wisdombrave.iteye.com/blog/546508
3 spring各种邮件发送
http://blog.csdn.net/lenolong/article/details/3970110
4 spring来发EMAIL
http://www.cnblogs.com/jackyrong/archive/2006/08/17/479812.html
5 使用spring发送邮件例
http://www.blogjava.net/amigoxie/archive/2007/04/28/114310.html
6 Spring Mail中文乱码问题
http://blog.csdn.net/matrixjava/article/details/3237772
7 国内常用邮箱客户端POP3和SMTP服务器大全
http://www.hiapk.com/thread-7912-1-1.html
写在前面的话
网上很多文章都是针对配置文件来说的,本文是对<spring各种邮件发送>这篇文章作了封装,使用spring发送Email更加方便
网易和其它很多公司现在都没有对外开放POP3/SMTP服务,可能你会碰到这样的错误:
org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException
我测试时是用的是:新浪的邮箱:smtp.sina.com也是可以的
如下设置:
Exception: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection
参考文章:http://zhidao.baidu.com/question/227409027.html
解答: 配置JavaMail的Properties时,不要指定mail.smtp.socketFactory.class,因为TLS使用的是普通的Socket。 然后指定属性mail.smtp.starttls.enable为true.
介绍
Spring邮件抽象层的主要包为org.springframework.mail。它包括了发送电子邮件的主要接口MailSender,和值对象SimpleMailMessage,
它封装了简单邮件的属性如from, to,cc, subject,text。 包里还包含一棵以MailException为根的checked Exception继承树,
它们提供了对底层邮件系统异常的高级别抽象.为了使用JavaMail中的一些特色, 比如MIME类型的信件, Spring提供了MailSender的一个子接口,
即org.springframework.mail.javamail.JavaMailSender。Spring还提供了一个回调接口org.springframework.mail.javamail.MimeMessagePreparator,
用于准备JavaMail的MIME信件.
工程环境:XP+Myeclipse6.5+JDK1.6
一 实现功能
1 封装了常用的四种发送Email的方法(文本,html,img,file),用户只要调用一个工厂类传递相应的邮件的属性如from, to,cc, subject,text,或者是消息对象
2 解决了发送邮件附件中的中文筹码问题,参见了<Spring Mail中文乱码问题>
3 支持链式风格
4 可以混合发送多种消息(text,html,img,file)
二 工程图片
或者你也可以这样,使用打包好的jar:email.spring.util.jar
,见附件
三 调用说明
1 发送文本消息
//默认空构造为发送文本类型
//默认空构造为发送文本类型
MailMessageFactory mms = new MailMessageFactory();
mms.setSubject("使用spring email 测试发送文本消息")
.setText("正文消息了。。。。")
.send();
2 发送Html格式消息
MailMessageFactory mms = new MailMessageFactory(SendMailType.HTML);
mms.setSubject("使用spring email 测试发送Html中文邮件")
.setText("<html><head><meta http-equiv='content-type' content='text/html; charset=GBK'>" +
"</head><body><h1>这里是咫尺天涯发送的邮件</h1></body></html>").send();
3 发送含有图片的消息
MailMessageFactory mms = new MailMessageFactory(SendMailType.HTML);
String text = "<html><body>欢迎访问咫尺天涯博客<br>"
+ "<a href='http://liuzidong.iteye.com/' target='_blank'>"
+ "<img src='cid:belle'></a><br><img src='cid:belle2'></body></html>";
//附件要嵌入到HTML中显示,则在IMG标签中用"cid:XXX"标记。
mms.setSubject("使用spring email 测试邮件中嵌套图片");
mms.setText(text);
File file = new File("c:\\5.jpg");
mms.setImgFile("belle", file);
File file2 = new File("c:\\4.jpg");
mms.setImgFile("belle2", file2);
mms.send();
4 发送含有附件的消息
MailMessageFactory mms = new MailMessageFactory(SendMailType.HTML);
mms.setSubject("使用spring email 测试发送附件");
File file = new File("c:\\1.zip");
mms.setAttachmentFile("jquery学习记录", file).send();
5 综合发送(文本,html,img,file)消息
MailMessageFactory mms = new MailMessageFactory(SendMailType.HTML);
mms.setSubject("使用spring email 测试发送邮件<包含html,img,file>等格式");
mms.setText("这是我的文本格式");
mms.setText("<html><head><h1>这里是咫尺天涯发送的邮件</h1></head><body>" +
"<h1><a href='http://liuzidong.iteye.com/' target='_blank'></h1><br>" +
"<img src='cid:belle'></a><br><img src='cid:belle2'>"+
"</body></html>");
//附件要嵌入到HTML中显示,则在IMG标签中用"cid:XXX"标记。
File file = new File("c:\\5.jpg");
mms.setImgFile("belle", file);
File file2 = new File("c:\\4.jpg");
mms.setImgFile("belle2", file2);
File file3 = new File("c:\\1.zip");
mms.setAttachmentFile("附件1", file3);
File file4 = new File("c:\\jquery学习记录.txt");
mms.setAttachmentFile("jquery学习记录", file4);
mms.send();
四 代码如下
1 消息发送类:MailMessageFactory
package net.liuzd.email.spring;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import net.liuzd.email.EmailEntity;
import net.liuzd.email.MailType;
import net.liuzd.email.SendMailType;
import net.liuzd.email.SendMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
/**
* Title: 消息发送类
* Description: Copyright: Copyright (c) 2011
* Company:http://liuzidong.iteye.com/ Makedate:2011-7-4 上午10:11:08
* @author liuzidong
* @version 1.0
* @since 1.0
*
*/
public class MailMessageFactory {
private SimpleMailMessage simpleMailMessage;
private MimeMessageHelper mimeMessageHelper;
private JavaMailSenderImpl senderImpl;
private MimeMessage mimeMessage;
private SendMailType sendMailType;
private SendMessage sendMessage;
private static final String ENCODING = EmailEntity.EMAIL_ENCODING;
/**
* 默认为发送文本类型
* */
public MailMessageFactory() {
this(SendMailType.TEXT);
}
/**
* 请显示指明文件类型为:TEXT,HTML,默认为文本类型
*
* */
public MailMessageFactory(SendMailType sendMailType){
this.sendMailType = sendMailType;
this.senderImpl = JavaMailFactory.getJavaMail();
this.mimeMessage = senderImpl.createMimeMessage();
sendMessage = new SendMessage();
try {
switch (this.sendMailType) {
case TEXT:
simpleMailMessage = new SimpleMailMessage();
break;
case HTML:
mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, ENCODING);
}
} catch (Exception e) {
e.fillInStackTrace();
}
}
/**
* @param to 接收者人地址
* @return
*/
public MailMessageFactory setTo(String ... to){
sendMessage.setTos(to);
return this;
}
/**发送标题*/
public MailMessageFactory setSubject(String subject){
sendMessage.setSubject(subject);
return this;
}
/**发送内容*/
public MailMessageFactory setText(String text){
sendMessage.addText(text);
return this;
}
/**
* 加入图片文件
* @param imageName 图片名称
* @param file 图片源
* @return
*/
public MailMessageFactory setImgFile(String imageName,File file){
try {
sendMessage.addFile(MailType.IMG,MimeUtility.encodeWord(imageName), file);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return this;
}
/**
* 加入图片文件
* @param imageName 图片名称
* @param filePath 图片路径
* @return
*/
public MailMessageFactory setImgFile(String imageName,String filePath){
setImgFile(imageName, new File(filePath));
return this;
}
/**
* 加入附件
* @param fileName 附件名称
* @param file 附件路径
* @return
*/
public MailMessageFactory setAttachmentFile(String fileName,String filePath){
setAttachmentFile(fileName, new File(filePath));
return this;
}
/**
* 加入附件
* @param fileName 附件名称
* @param file 附件源
* @return
*/
public MailMessageFactory setAttachmentFile(String fileName,File file){
try {
sendMessage.addFile(MailType.FILE,MimeUtility.encodeWord(fileName),file);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return this;
}
/**发送消息,你调用此方法进行Email消息的发送*/
public void send(){
//消息发送前,检查发送人地址,接收人地址是否为空,为空就设置为配置文件中的地址
sendMessage.setForm(EmailEntity.EMAIL_FROM);
//检查接收人地址是否为空
String [] tos = sendMessage.getTos();
if(null == tos || tos.length == 0){
tos = new String[]{EmailEntity.EMAIL_TO};
sendMessage.setTos(tos);
}
long startTime = System.currentTimeMillis();
//发送普通文本
if(sendMailType == SendMailType.TEXT){
sendTextMessage();
}else{
sendHtmlImgFileMessage();
}
long endTime = System.currentTimeMillis();
System.out.println(sendMailType + "成功!,耗费时间: " + (endTime - startTime)+"毫秒!");
}
/**
* 发送html,图片,附件的消息
*/
private void sendHtmlImgFileMessage() {
try {
mimeMessageHelper.setTo(sendMessage.getTos());
mimeMessageHelper.setFrom(sendMessage.getForm());
String subject = sendMessage.getSubject();
if(null != subject && !"".equals(subject)){
mimeMessageHelper.setSubject(subject);
}
String text = sendMessage.getSendTexts();
if(null != text && !"".equals(text)){
mimeMessageHelper.setText(text,true);
}
//检查图片或者文件集合是否为空
int imgSize = sendMessage.getImages().size();
if(imgSize > 0){
List<SendMessage> lists = sendMessage.getImages();
FileSystemResource fsr = null;
String imgName = null;
for(SendMessage entity : lists){
fsr = new FileSystemResource(entity.getFile());
imgName = entity.getImgName();
//如果为图片类型就调用addInline,否则就调用:addAttachment方法^_^
if(entity.getMailType() == MailType.IMG)
mimeMessageHelper.addInline(imgName, fsr);
else
mimeMessageHelper.addAttachment(imgName, fsr);
}
fsr = null;
}
} catch (MessagingException e) {
e.printStackTrace();
}
senderImpl.send(mimeMessage);
}
/**
* 发送文本消息
*/
private void sendTextMessage() {
simpleMailMessage.setTo(sendMessage.getTos());
simpleMailMessage.setFrom(sendMessage.getForm());
String subject = sendMessage.getSubject();
if(null != subject && !"".equals(subject)){
simpleMailMessage.setSubject(subject);
}
String text = sendMessage.getSendTexts();
if(null != text && !"".equals(text)){
simpleMailMessage.setText(text);
}
senderImpl.send(simpleMailMessage);
}
/**
* @param subject 发送标题
* @param text 发送内容
* @param to 接收人地址
*/
public void send(String subject,String text,String ... to){
sendMessage(subject, text, to);
}
private void sendMessage(String subject, String text, String... to) {
setTo(to);
setSubject(subject);
setText(text);
}
public SendMessage getSendMessage() {
return sendMessage;
}
/***
* 接收一个消息对象
* */
public MailMessageFactory setSendMessage(SendMessage sendMessage) {
this.sendMessage = sendMessage;
return this;
}
}
2 邮件发送类型:SendMailType
package net.liuzd.email;
/**
*Title: 邮件发送类型
*Description:
*Copyright: Copyright (c) 2011
*Company:http://liuzidong.iteye.com/
*Makedate:2011-7-4 上午09:59:08
* @author liuzidong
* @version 1.0
* @since 1.0
*
*/
public enum SendMailType {
/**
* 文本类型
* */
TEXT,
/**
* HTML类型,包含图片与附件内容
* **/
HTML;
@Override
public String toString() {
String message = null;
switch (this) {
case TEXT:
message = "发送文本消息";
break;
case HTML :
message = "发送html消息";
break;
}
return message;
}
}
3 读取配置文件类:ReadConfigEmail
public class ReadConfigEmail {
private static Properties mailProps = new Properties();
private static final String EMAILPROPERTIES = "mail.properties";
static {
try {
InputStream inStream = ReadConfigEmail.class.getClassLoader()
.getResourceAsStream(EMAILPROPERTIES);
mailProps.load(inStream);
} catch (Exception ex) {
throw new RuntimeException("读取配置文件出错了..." + ex.getMessage(), ex);
}
}
public static Properties getProperty() {
return mailProps;
}
public static String getPropertyByKey(String key) {
return mailProps.getProperty(key);
}
}
4 消息对象:SendMessage
public class SendMessage {
private String [] tos;
private String subject;
private String imgName;
private File file;
private MailType mailType;
private String form;
private List<String> texts = new ArrayList<String>();
//图片集合
private List<SendMessage> images = new ArrayList<SendMessage>();
public MailType getMailType() {
return mailType;
}
public void setMailType(MailType mailType) {
this.mailType = mailType;
}
public void addFile(MailType mailType,String imgName,File file){
images.add(new SendMessage(mailType,imgName,file));
}
public void addText(String text){
texts.add(text);
}
public SendMessage(MailType mailType,String imgName, File file) {
super();
this.mailType = mailType;
this.imgName = imgName;
this.file = file;
}
public List<SendMessage> getImages() {
return images;
}
public void setImages(List<SendMessage> images) {
this.images = images;
}
public String getForm() {
return form;
}
public void setForm(String form) {
this.form = form;
}
public String getImgName() {
return imgName;
}
public void setImgName(String imgName) {
this.imgName = imgName;
}
public String[] getTos() {
return tos;
}
public void setTos(String[] tos) {
this.tos = tos;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public SendMessage() {
}
public SendMessage(String[] tos, String subject, String text) {
super();
this.tos = tos;
this.subject = subject;
addText(text);
}
public String getSendTexts(){
StringBuilder sbr = new StringBuilder();
List<String> texts = getTexts();
for(String text : texts){
sbr.append(text);
}
return sbr.toString();
}
@Override
public String toString() {
StringBuilder sbrTos = new StringBuilder();
for(String to : tos){
sbrTos.append(to).append(",");
}
String sbrText = sbrTos.substring(0,sbrTos.length()-1);
return new StringBuilder()
.append("接收人地址: ").append(sbrText)
.append(",发送人地址: ").append(form)
.append(",发送标题: ").append(subject)
.append(",发送内容: ").append(getSendTexts())
.toString();
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public List<String> getTexts() {
return texts;
}
public void setTexts(List<String> texts) {
this.texts = texts;
}
}
5 邮件发送服务器:JavaMailFactory
public class JavaMailFactory {
/***
* 此处也可修改为
* private JavaMailSenderImpl javaMailSenderImpl;
* ... 省略set,get,方便使用spring注入
* */
private static JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
static{
senderImpl.setHost(EmailEntity.EMAIL_HOST);
senderImpl.setUsername(EmailEntity.EMAIL_USERNAME);
senderImpl.setPassword(EmailEntity.EMAIL_PASSWORD);
senderImpl.setJavaMailProperties(EmailEntity.safetyProperties);
}
public static JavaMailSenderImpl getJavaMail(){
return senderImpl;
}
}
6 Email实体:EmailEntity
public class EmailEntity {
/**邮件服务器*/
private static final String EMAIL_HOST_KEY = "mail.host";
public static final String EMAIL_HOST = ReadConfigEmail.getPropertyByKey(EMAIL_HOST_KEY);
/**用户名*/
private static final String EMAIL_USERNAME_KEY = "mail.username";
public static final String EMAIL_USERNAME = ReadConfigEmail.getPropertyByKey(EMAIL_USERNAME_KEY);
/**用户密码*/
private static final String EMAIL_PASSWORD_KEY = "mail.password";
public static final String EMAIL_PASSWORD = ReadConfigEmail.getPropertyByKey(EMAIL_PASSWORD_KEY);
/**接收人*/
private static final String EMAIL_TO_KEY = "mail.to";
public static final String EMAIL_TO = ReadConfigEmail.getPropertyByKey(EMAIL_TO_KEY);
/**发送人*/
private static final String EMAIL_FROM_KEY = "mail.from";
public static final String EMAIL_FROM = ReadConfigEmail.getPropertyByKey(EMAIL_FROM_KEY);
/**服务器进行认证,认证用户名和密码是否正确*/
private static final String EMAIL_SMTP_AUTH_KEY = "mail.smtp.auth";
public static final String EMAIL_SMTP_AUTH = ReadConfigEmail.getPropertyByKey(EMAIL_SMTP_AUTH_KEY);
/**超时时间设定*/
private static final String EMAIL_SMTP_TIMEOUT_KEY = "mail.smtp.timeout";
public static final String EMAIL_SMTP_TIMEOUT = ReadConfigEmail.getPropertyByKey(EMAIL_SMTP_TIMEOUT_KEY);
/**编码设置*/
private static final String EMAIL_ENCODING_KEY = "mail.encoding";
public static final String EMAIL_ENCODING = ReadConfigEmail.getPropertyByKey(EMAIL_ENCODING_KEY);
private static final String EMAIL_SMTP_STARTTLS_KEY = "mail.smtp.starttls.enable";
public static final String EMAIL_SMTP_STARTTLS = ReadConfigEmail.getPropertyByKey(EMAIL_SMTP_STARTTLS_KEY);
//private static final String EMAIL_SMTP_SOCKETFACTORY_CLASS_KEY = "mail.smtp.socketFactory.class";
//public static final String EMAIL_SMTP_SOCKETFACTORY_CLASS = ReadConfigEmail.getPropertyByKey(EMAIL_SMTP_SOCKETFACTORY_CLASS_KEY);
/**安全认证设置*/
public static Properties safetyProperties = new Properties();
static{
//调试信息,可以取消
//System.setProperty( "javax.net.debug", "ssl");
/**
* #配置JavaMail的Properties时,不要指定“mail.smtp.socketFactory.class”,
#因为TLS使用的是普通的Socket。然后指定属性“mail.smtp.starttls.enable”为“true”。
* */
safetyProperties.put(EMAIL_SMTP_AUTH_KEY, EMAIL_SMTP_AUTH);
safetyProperties.put(EMAIL_SMTP_TIMEOUT_KEY, EMAIL_SMTP_TIMEOUT);
safetyProperties.put(EMAIL_SMTP_STARTTLS_KEY, EMAIL_SMTP_STARTTLS);
//safetyProperties.put(EMAIL_SMTP_SOCKETFACTORY_CLASS_KEY, EMAIL_SMTP_SOCKETFACTORY_CLASS);
}
}
7 MailType.java
public enum MailType {
/**
* 图片类型
* */
IMG,
/**
* 文件类型
* */
FILE;
@Override
public String toString() {
String message = null;
switch (this) {
case IMG :
message = ",包含图片";
default:
message = ",包含附件";
break;
}
return message;
}
}
8 mail.properties
#新浪邮件服务器
mail.host=smtp.sina.com
mail.smtp.auth=true
mail.smtp.timeout=25000
mail.encoding=utf-8
mail.smtp.starttls.enable=true;
#mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
#Email地址
mail.username=XXX
#Email密码
mail.password=XXX
#发送人地址
[email protected]
#收件人地址
[email protected]