1、spring配置文件(src/applicationContext.xml ):
<bean id="mailSender"class="org.springframework.mail.javamail.JavaMailSenderImpl"><property name="host" value="222.173.82.207"></property><property name="javaMailProperties"><props><prop key="mail.smtp.auth">true</prop><prop key="mail.smtp.timeout">25000</prop></props></property><property name="username" value="tiandeqing@ecode.net.cn" /><property name="password" value="密碼" /></bean><bean id="freeMarker"class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"><property name="templateLoaderPath" value="classpath:mail" /><!--指定模板文件目錄--><property name="freemarkerSettings"><!-- 設(shè)置FreeMarker環(huán)境屬性--><props><prop key="template_update_delay">1800</prop><!--刷新模板的周期,單位為秒--><prop key="default_encoding">UTF-8</prop><!--模板的編碼格式 --><prop key="locale">zh_CN</prop><!-- 本地化設(shè)置--></props></property></bean>
2、Java代碼:
給指定的單個用戶發(fā)送普通文本郵件:SpringMail.java
package aaa;import java.io.StringWriter;import java.util.HashMap;import java.util.Map;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import freemarker.template.Configuration;import freemarker.template.Template;public class SpringMail {private Configuration cfg = new Configuration();public static void main(String[] args) throws Exception {ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");SpringMail springMail = new SpringMail();springMail.sendMail(sender);}private void sendMail(JavaMailSender sender) throws Exception {SimpleMailMessage mail = new SimpleMailMessage();mail.setTo("tiandeqing@ecode.net.cn"); //接收人mail.setFrom("tiandeqing@ecode.net.cn"); //發(fā)送人mail.setSubject("test by amigo");//嵌入ftl模版cfg.setClassForTemplateLoading(getClass(), "/mail");Map root = new HashMap();root.put("username", "sucre"); //模板變量Template t = cfg.getTemplate("notify-mail.ftl");StringWriter writer = new StringWriter();t.process(root, writer);//把模版內(nèi)容寫入郵件中mail.setText(writer.toString());sender.send(mail);System.out.println("郵件發(fā)送成功!");}}
給指定的多個用戶發(fā)送含有附件的html郵件,SpringMail_Batch_Attach_HTML.java
package aaa;import java.io.File;import java.io.StringWriter;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeUtility;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;import freemarker.template.Configuration;import freemarker.template.Template;public class SpringMail_Batch_Attach_HTML {private Configuration cfg = new Configuration();private static JavaMailSender sender = null;private static FreeMarkerConfigurer freeMarker = null;public static void main(String[] args) throws Exception {// initApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");SpringMail_Batch_Attach_HTML.sender = sender;SpringMail_Batch_Attach_HTML.freeMarker = (FreeMarkerConfigurer) ctx.getBean("freeMarker");SpringMail_Batch_Attach_HTML springMail = new SpringMail_Batch_Attach_HTML();//發(fā)送簡單郵件springMail.sendMail(sender);//給某個人發(fā)送郵件,基于模板springMail.sendMessage("灑江河風(fēng)景阿嫂法拉", "wytdq@126.com");//給某些人發(fā)送郵件,帶附件List toList = new ArrayList();toList.add("xxx@sina.COM");toList.add("xxx@163.COM");toList.add("TIANDEQING@ECODE.NET.CN");springMail.sendBatchEmail("郵件批量發(fā)送測試", toList);}// 發(fā)送一封文本郵件給一個收件人private void sendMail(JavaMailSender sender) throws Exception {SimpleMailMessage mail = new SimpleMailMessage();mail.setTo("tiandeqing@ecode.net.cn"); // 接收人mail.setFrom("tiandeqing@ecode.net.cn"); // 發(fā)送人mail.setSubject("test by amigo");// 嵌入ftl模版cfg.setClassForTemplateLoading(getClass(), "/mail");Map root = new HashMap();root.put("username", "sucre"); // 模板變量Template t = cfg.getTemplate("notify-mail.ftl");StringWriter writer = new StringWriter();t.process(root, writer);// 把模版內(nèi)容寫入郵件中mail.setText(writer.toString());sender.send(mail);System.out.println("郵件發(fā)送成功!");}/*** 發(fā)送帶模板的單個html格式郵件** @throws Exception*/public void sendMessage(String content, String address) throws Exception {MimeMessage msg = sender.createMimeMessage();// 設(shè)置utf-8或GBK編碼,否則郵件會有亂碼,true表示為multipart郵件MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");helper.setTo(address); // 郵件接收地址helper.setFrom("tiandeqing@ecode.net.cn"); // 郵件發(fā)送地址,這里必須和xml里的郵件地址相同一致helper.setSubject("測試ccc"); // 主題String htmlText = getMailText(content); // 使用模板生成html郵件內(nèi)容helper.setText(htmlText, true); // 郵件內(nèi)容,注意加參數(shù)true,表示啟用html格式sender.send(msg); // 發(fā)送郵件System.out.println("sendMessage(String content,String address) OK");}/*** 批量發(fā)送多媒體郵件* */public void sendBatchEmail(String content, List address)throws MessagingException, UnsupportedEncodingException {MimeMessage msg = sender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");StringBuffer html = new StringBuffer();html.append("<html>");html.append("<head>");html.append("<meta http-equiv='Content-Type' content='text/html; charset=gbk'>");html.append("</head>");html.append("<body bgcolor='#ccccff'>");html.append("<center>");html.append("<h1>你好,Jarry</h1>").append(content);html.append("<img src='cid:myimg'>");//顯示圖片html.append("<p>logo:");html.append("<img src='cid:vedio'>");html.append("</center>");html.append("</body>");html.append("</html>");String toList = getMailList(address);InternetAddress[] iaToList = new InternetAddress().parse(toList);msg.setRecipients(Message.RecipientType.TO, iaToList);helper.setFrom("tiandeqing@ecode.net.cn");helper.setSubject("批量發(fā)送測試");helper.setText(html.toString(), true);// 添加內(nèi)嵌文件,第1個參數(shù)為cid標(biāo)識這個文件,第2個參數(shù)為資源helper.addInline("myimg", new File("D:\\My Documents\\My Pictures\\tian.JPG")); // 附件內(nèi)容helper.addInline("vedio", new File("D:\\My Documents\\My Pictures\\vedio.JPG"));File file = new File("D:\\My Documents\\My Pictures\\hibernate框架.jpg");// 這里的方法調(diào)用和插入圖片是不同的(插入到最后,并且直接顯示),使用MimeUtility.encodeWord()來解決附件名稱的中文問題helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);// 如果主題出現(xiàn)亂碼,可以使用該函數(shù),也可以使用下面的函數(shù)// helper.setSubject(MimeUtility.encodeText(String text,String// charset,String encoding))// 第2個參數(shù)表示字符集,第三個為目標(biāo)編碼格式。// MimeUtility.encodeWord(String word,String charset,String encoding)sender.send(msg);System.out.println("sendBatchEmail OK");}/*** 集合轉(zhuǎn)換字符串*/public String getMailList(List<String> to) {StringBuffer toList = new StringBuffer();int length = to.size();if (to != null && length < 2) {toList.append(to.get(0));} else {for (int i = 0; i < length; i++) {toList.append(to.get(i));if (i != (length - 1)) {toList.append(",");}}}return toList.toString();}// 通過模板構(gòu)造郵件內(nèi)容,參數(shù)content將替換模板文件中的${content}標(biāo)簽。private String getMailText(String content) throws Exception {String htmlText = "";// 通過指定模板名獲取FreeMarker模板實例Template tpl = freeMarker.getConfiguration().getTemplate("registerUser.ftl");Map map = new HashMap(); // FreeMarker通過Map傳遞動態(tài)數(shù)據(jù)map.put("content", content); // 注意動態(tài)數(shù)據(jù)的key和模板標(biāo)簽中指定的屬性相匹配// 解析模板并替換動態(tài)數(shù)據(jù),最終content將替換模板文件中的${content}標(biāo)簽。htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);return htmlText;}}
3、模板文件src/mail/notify-mail.ftl :
歡迎加入!親愛的${username}請點擊鏈接完成注冊:如果您的email程序不支持鏈接點擊,請將上面的地址拷貝至您的瀏覽器(如IE)的地址欄進入****。您可以在***:查看最新的影視資料,查看各種相關(guān)消費產(chǎn)品,在這里交友,灌水……;希望您在**度過快樂的時光!-(這是一封自動產(chǎn)生的email,請勿回復(fù)。)
模板文件src/mail/registerUser.ftl :
<html><head><meta http-equiv="content-type" content="text/html;charset=utf8"></head><body>恭喜您成功注冊!您的用戶名為:<font color='red' size='30'>${content}</font></body></html>
4、例子使用了FreeMarker。
FreeMarker就是一種用Java編寫的模板引擎,它根據(jù)模板輸出多種規(guī)格的文本。
特別指出的是,F(xiàn)reeMarker與Web應(yīng)用框架無關(guān),它同樣可以應(yīng)用在非Web應(yīng)用程序環(huán)境中。
程序目錄結(jié)構(gòu):
注意在執(zhí)行代碼前,請確認已經(jīng)將activation.jar,commons-logging-1.0.4.jar,mail.jar和spring.jar載入工程,并且服務(wù)器的25端口已開啟。