在以前的工作项目中,也接触过javamail来发送简单的邮件,但是最近的一个项目在用javamail来发送html格式的邮件时,却遇到了点小麻烦。因为客户要求要把在后台生成的3D报表图片(用JFreeChart来实现)嵌入到html中。其实发送html格式的邮件倒是没有什么困难,难就难在如何把在服务器端生成的3D图片也发送出去,并且不能把3D的图片存储在server上,因为是Web应用,访问量甚是惊人,如果每个用户都生成几个3D图片,不用很久服务器的存储空间就难以承受了。还好经过我耐心地试验,问题终于得到了圆满解决,在此记录下来,以备不时之需,同时分享给像前几天的我一样被这个问题困扰的同行们。
首先配置spring的xml文件:
<? xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
< beans >
< bean id ="mailsender" class ="org.springframework.mail.javamail.JavaMailSenderImpl" >
< property name ="host" >
< value > smtp.163.com </ value >
</ property >
< property name ="username" >
< value > youruser </ value >
</ property >
< property name ="password" >
< value > yourpassword </ value >
</ property >
< property name ="javaMailProperties" >
< props >
< prop key ="mail.smtp.auth" > true </ prop >
</ props >
</ property >
</ bean >
< bean id ="mailmessage" class ="org.springframework.mail.SimpleMailMessage" >
< property name ="to" >
< value > youruser@163.com </ value >
</ property >
< property name ="from" >
< value > youruser@163.com </ value >
</ property >
< property name ="subject" >
< value > A sample mail </ value >
</ property >
</ bean >
</ beans >
邮件工厂,采用工厂模式:
/** */
/**
*
*/
package
com.kevin.springmail;

import
java.io.File;
import
java.io.IOException;

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

import
org.apache.commons.logging.Log;
import
org.apache.commons.logging.LogFactory;
import
org.apache.log4j.BasicConfigurator;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import
org.springframework.core.io.FileSystemResource;
import
org.springframework.core.io.UrlResource;
import
org.springframework.mail.SimpleMailMessage;
import
org.springframework.mail.javamail.JavaMailSenderImpl;
import
org.springframework.mail.javamail.MimeMessageHelper;


/** */
/**
* @author Administrator
* @date 2006-9-15
* @time 22:16:34
*/

public
class
MailFactory
...
{
private static final Log logger = LogFactory.getLog(MailFactory.class);
private static final ApplicationContext context;

/** *//**
* 初始化beans
*/

static ...{
//加载log4j日志记录
BasicConfigurator.configure();
String springbean = "com/kevin/springmail/springmail.xml";
context = new ClassPathXmlApplicationContext(springbean);
logger.info("初始化beans springmail.xml 完成!");
}

/** *//**
* 发送简单的邮件信息,邮件的内容都是纯文本的内容
*
*/

public static void sendSimpleMessageMail()...{
SimpleMailMessage mailmessage = (SimpleMailMessage)context.getBean("mailmessage");
JavaMailSenderImpl mailsender = (JavaMailSenderImpl)context.getBean("mailsender");
mailmessage.setText("你好,Jarry!");
mailsender.send(mailmessage);
logger.info("simple mail has bean sent !");
}

/** *//**
* 发送HTML格式的邮件,HTML格式中带有图片的,
* 图片的来源是Server端的文件系统。(图片就是文件系统的)
* @throws MessagingException
* @throws IOException
*/

public static void sendMimeMessageMail() throws MessagingException, IOException...{
JavaMailSenderImpl mailsender = (JavaMailSenderImpl)context.getBean("mailsender");
MimeMessage mimeMessage = mailsender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "GB2312");
StringBuffer html = new StringBuffer();
html.append("<html>");
html.append("<head>");
html.append("<meta http-equiv='Content-Type' content='text/html; charset=gb2312'>");
html.append("</head>");
html.append("<body bgcolor='#ccccff'>");
html.append("<center>");
html.append("<h1>你好,Jarry</h1>");
html.append("<img src='cid:img'>");
html.append("<p>logo:");
html.append("<img src='cid:logo'>");
html.append("</center>");
html.append("</body>");
html.append("</html>");
helper.setText(html.toString(), true);
FileSystemResource image = new FileSystemResource(new File("icon.gif"));
helper.addInline("img",image);
FileSystemResource logo = new FileSystemResource(new File("logo.gif"));
helper.addInline("logo",logo);
helper.setFrom("green006@163.com");
helper.setTo("green006@163.com");
helper.setSubject("spring javamail test");
logger.info(mimeMessage.getContentID());
logger.info(mimeMessage.getContent());
mailsender.send(mimeMessage);
logger.info("mime mail has bean sent !");
}

/** *//**
* 发送带动态图象的HTML邮件,所谓动态图象就是在发送邮件时
* 动态地生成一个图片,然后再随HTML格式的邮件发送出去。
* @throws MessagingException
* @throws IOException
*
*/

public static void sendDynamicImageMail() throws MessagingException, IOException...{
JavaMailSenderImpl mailsender = (JavaMailSenderImpl)context.getBean("mailsender");
MimeMessage mimeMessage = mailsender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "GB2312");
StringBuffer html = new StringBuffer();
html.append("<html>");
html.append("<head>");
html.append("<meta http-equiv='Content-Type' content='text/html; charset=gb2312'>");
html.append("</head>");
html.append("<body bgcolor='#ccccff'>");
html.append("<center>");
html.append("<h1>你好,Jarry</h1>");
html.append("<img src='cid:png'>");//cid:png中的png就是下面的helper.addInline("png",image);中的png
html.append("</body>");
html.append("</html>");
//设定邮件的正文内容
helper.setText(html.toString(), true);
//new一个UrlResource对象,注意http://localhost:8080/springtiles/makechart.png看起来好像一个png格式的
//图片,其实makechart.png本质上是一个Servlet,在这个Servlet中用JFreeChart构造了一个3D的图象。
UrlResource image = new UrlResource("http://localhost:8080/springtiles/makechart.png");
//把生成的image图象添加到邮件信息中
helper.addInline("png",image);
helper.setFrom("green006@163.com");
helper.setTo("green006@163.com");
helper.setSubject("spring javamail test");
logger.info(mimeMessage.getContentID());
logger.info(mimeMessage.getContent());
mailsender.send(mimeMessage);
logger.info("dynamic image mail has bean sent !");
}

/** *//**
* 发送带附件的电子邮件,包括文件名是中文的。
* (中文比较特殊些,不然会出现乱码)
*
* @throws MessagingException
* @throws IOException
*/

public static void sendMailWithAttachment() throws MessagingException, IOException...{
JavaMailSenderImpl mailsender = (JavaMailSenderImpl)context.getBean("mailsender");
MimeMessage mimeMessage = mailsender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "GB2312");
StringBuffer html = new StringBuffer();
html.append("<html>");
html.append("<head>");
html.append("<meta http-equiv='Content-Type' content='text/html; charset=gb2312'>");
html.append("</head>");
html.append("<body bgcolor='#ccccff'>");
html.append("<center>");
html.append("<h1>你好,Jarry</h1>");
html.append("<p>logo:");
html.append("<img src='cid:logo'>");
html.append("</center>");
html.append("</body>");
html.append("</html>");
helper.setText(html.toString(), true);
FileSystemResource logo = new FileSystemResource(new File("logo.gif"));
helper.addInline("logo",logo);
//添加附件
File file = new File("build.xml");
helper.addAttachment("build.xml",file);
//添加中文名的,不做下面的处理会出现乱码的。
String filename = MimeUtility.encodeText(new String("个人助理-公元农历.mht".getBytes(),"GB2312"),"GB2312","B");
File f = new File("个人助理-公元农历.mht");
helper.addAttachment(filename,f);
helper.setFrom("green006@163.com");
helper.setTo("green006@163.com");
helper.setSubject("spring javamail test");
logger.info(mimeMessage.getContentID());
logger.info(mimeMessage.getContent());
mailsender.send(mimeMessage);
logger.info("a mime mail with an attachment has bean sent !");
}

}
生成3D图象的servlet:
/** */
/**
*
*/
package
com.kevin.springmail;

import
java.io.IOException;

import
javax.servlet.ServletException;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;

import
org.apache.commons.logging.Log;
import
org.apache.commons.logging.LogFactory;

import
com.kevin.jfreechart.education.EducationAccount;


/** */
/**
* @author Administrator
* @date 2006-9-16
* @time 0:45:47
*/

public
class
ChartServlet
extends
HttpServlet
...
{
private final Log logger = LogFactory.getLog(this.getClass());

/** *//**
*
*/
private static final long serialVersionUID = 1L;
private final String CONTENS_TYPE ="IMAGE/PNG";

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...{
response.setContentType(CONTENS_TYPE);
//利用JFreeChart构建生成3D的图表
EducationAccount assetBar = new EducationAccount();
assetBar.drawBar3D(response.getOutputStream());
logger.info("完成在servlet中输出image!");
}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...{
// TODO Auto-generated method stub
doGet(request,response);
}


}
简单测试一下:
/** */
/**
*
*/
package
com.kevin.springmail;

import
java.io.IOException;
import
java.net.URISyntaxException;

import
javax.mail.MessagingException;


/** */
/**
* @author Administrator
* @date 2006-9-15
* @time 22:36:29
*/

public
class
MailTest
...
{


/** *//**
* @param args
* @throws MessagingException
* @throws IOException
* @throws URISyntaxException
*/

public static void main(String[] args) throws MessagingException, IOException, URISyntaxException ...{
// TODO Auto-generated method stub
//MailFactory.sendSimpleMessageMail();
//MailFactory.sendMimeMessageMail();
MailFactory.sendMailWithAttachment();
}

}
首先配置spring的xml文件:
<? xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
< beans >
< bean id ="mailsender" class ="org.springframework.mail.javamail.JavaMailSenderImpl" >
< property name ="host" >
< value > smtp.163.com </ value >
</ property >
< property name ="username" >
< value > youruser </ value >
</ property >
< property name ="password" >
< value > yourpassword </ value >
</ property >
< property name ="javaMailProperties" >
< props >
< prop key ="mail.smtp.auth" > true </ prop >
</ props >
</ property >
</ bean >
< bean id ="mailmessage" class ="org.springframework.mail.SimpleMailMessage" >
< property name ="to" >
< value > youruser@163.com </ value >
</ property >
< property name ="from" >
< value > youruser@163.com </ value >
</ property >
< property name ="subject" >
< value > A sample mail </ value >
</ property >
</ bean >
</ beans >
邮件工厂,采用工厂模式:



























































































































































































































生成3D图象的servlet:

























































简单测试一下:





































Trackback: http://tb.blog.youkuaiyun.com/TrackBack.aspx?PostId=1240526