以下是我对spring发送邮件的总结:
分别使用了两种方法:单例模式和属性全注入的方法。
发送模式又分为:单发,群发。
可发送:text,html模板,附件等。
1、单例模式(单发,群发text)
在classpath底下新建application-mail.xml,内容如下:
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"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
- <!-- 注意:这里的参数(如用户名、密码)都是针对邮件发送者的 -->
- <bean id="mailSender"
- class = "org.springframework.mail.javamail.JavaMailSenderImpl" >
- <property name="host" >
- <value>smtp.163 .com</value>
- </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>username@163 .com</value>
- </property>
- <property name="password" >
- <value>password</value>
- </property>
- </bean>
- </beans>
或者把以上的Beans配置到applicaiont.xml里面也可以。
发送text格式的Email类:
- /
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import org.springframework.mail.SimpleMailMessage;
- import org.springframework.mail.javamail.JavaMailSender;
- public class EmailUtil {
- private static EmailUtil emailUtil = null ;
- public ApplicationContext ctx = null ;
- private EmailUtil() {
- //获取上下文
- ctx = new ClassPathXmlApplicationContext( "applicationContext-mail.xml" );
- }
- /**
- *
- * @function:获得单例
- */
- public static EmailUtil getInstance()
- {
- if (emailUtil== null )
- {
- synchronized (EmailUtil. class )
- {
- if (emailUtil== null ) {
- emailUtil = new EmailUtil();
- }
- }
- }
- return emailUtil;
- }
- public void sentEmails(String emails,String subject,String text)
- {
- //获取JavaMailSender bean
- JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender" );
- //SimpleMailMessage只能用来发送text格式的邮件
- SimpleMailMessage mail = new SimpleMailMessage();
- String email[] = emails.split(";" );
- for ( int i= 0 ;i<email.length;i++) {
- try {
- mail.setTo(email[i]);//接受者
- mail.setFrom("username@163.com" );
- mail.setSubject(subject);//主题
- mail.setText(text);//邮件内容
- sender.send(mail);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * @function:测试邮件发送
- */
- public static void main(String[] args) {
- String mail_title = "注册成功" ;
- String mail_content = "恭喜!您已经注册成功.<BR>欢迎使用本网站,主页地址:<a href='http://www.baidu.com'/>" ;
- EmailUtil email = EmailUtil.getInstance();
- email.sentEmails("username@163.com" ,mail_title,mail_content);
- }
- }
2.属性全注入的方法(单发,群发html模板)
FreeMarker是一个被广泛使用的模板框架,Spring可以很好的支持该框架。Spring为FreeMarker提供了一个 FreeMarkerConfigurer类,通过此类可方便地创建FreeMarker的基础环境,Spring提供 FreeMarkerTemplateUtils工具类来完成解析模板的任务。下面以用户注册成功后发送的模板文件 registerUser.ftl,${content}标签代表一个可被替换的动态属性。FreeMarker模板的标签支持级联属性, 如${user.id}则表示user对象的id属性。在配置文件中已设置好模板目录,所以可在类中直接用模板文件名来定位模板文件。模板文件用UTF- 8编码格式,避免中文乱码。通过设置template_update_delay属性,可让FreeMarker定期刷新模板,从而使应用程序在不重启下 更新模板。
- < html >
- < head >
- < meta http-equiv = "content-type" content = "text/html;charset=utf8" >
- </ head >
- < body >
- 恭喜您成功注册!您的用户名为:< font color = 'red' size = '30' > ${content} </ font >
- </ body >
- </ html >
- <? xml version = "1.0" encoding = "UTF-8" ?>
- < beans xmlns = "http://www.springframework.org/schema/beans"
- xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
- xmlns:aop = "http://www.springframework.org/schema/aop"
- xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
- <!-- 注意:这里的参数(如用户名、密码)都是针对邮件发送者的 -->
- < bean id = "mailSender"
- class = "org.springframework.mail.javamail.JavaMailSenderImpl" >
- < property name = "host" >
- < value > smtp.163.com </ value >
- </ 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 > username@163.com </ value >
- </ property >
- < property name = "password" >
- < value > password </ value >
- </ property >
- </ bean >
- </ beans >
- < bean id = "freeMarker" class = "org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer" >
- < property name = "templateLoaderPath" value = "classpath:mailTemplate" /> <!--指定模板文件目录-->
- < property name = "freemarkerSettings" > <!-- 设置FreeMarker环境属性-->
- < props >
- < prop key = "template_update_delay" > 1800 </ prop > <!--刷新模板的周期,单位为秒-->
- < prop key = "default_encoding" > UTF-8 </ prop > <!--模板的编码格式 -->
- < prop key = "locale" > zh_CN </ prop > <!-- 本地化设置-->
- </ props >
- </ property >
- </ bean >
- <!-- ************************ Email Service配置 ********************************* -->
- < bean id = "emailService" class = "EmailService" >
- < property name = "sender" ref = "mailSender" > </ property >
- < property name = "freeMarkerConfigurer" ref = "freeMarker" > </ property >
- </ bean >
- </ beans >
- import javax.mail.MessagingException;
- import org.springframework.mail.javamail.JavaMailSender;
- import org.springframework.ui.freemarker.*;
- import org.springframework.web.servlet.view.freemarker.*;
- import freemarker.template.*;
- public abstract class EmailAbstract {
- protected String from;
- protected String subject;
- protected JavaMailSender sender;
- protected FreeMarkerConfigurer freeMarkerConfigurer= null ; //FreeMarker的技术类
- public String getFrom() {
- return from;
- }
- public void setFrom(String from) {
- this .from = from;
- }
- public String getSubject() {
- return subject;
- }
- public void setSubject(String subject) {
- this .subject = subject;
- }
- public JavaMailSender getSender() {
- return sender;
- }
- public void setSender(JavaMailSender sender) {
- this .sender = sender;
- }
- public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
- this .freeMarkerConfigurer = freeMarkerConfigurer;
- }
- /**
- * 发送单个html格式邮件
- */
- public abstract void sendEmail(String content,String address);
- /**
- * 批量发送html格式邮件
- */
- public abstract void sendBatchEmail(String content,List<String> address);
- }
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- import org.springframework.mail.javamail.MimeMessageHelper;
- import org.springframework.ui.freemarker.*;
- import org.springframework.web.servlet.view.freemarker.*;
- import freemarker.template.*;
- public class EmailService extends EmailAbstract {
- /**
- * 发送带模板的单个html格式邮件
- */
- public void sendMessage(String content,String address) throws MessagingException {
- MimeMessage msg = sender.createMimeMessage();
- //设置utf-8或GBK编码,否则邮件会有乱码,true表示为multipart邮件
- MimeMessageHelper helper = new MimeMessageHelper(msg, true , "utf-8" );
- helper.setTo(address); //邮件接收地址
- helper.setFrom(from); //邮件发送地址,这里必须和xml里的邮件地址相同一致
- helper.setSubject(subject); //主题
- String htmlText = getMailText(content); //使用模板生成html邮件内容
- helper.setText(htmlText, true ); //邮件内容,注意加参数true,表示启用html格式
- sender.send(msg); //发送邮件
- }
- /**
- * 批量发送带附件的html格式邮件
- */
- public void sendBatchEmail(String content,List<String> address) throws MessagingException {
- MimeMessage msg = sender.createMimeMessage();
- MimeMessageHelper helper = new MimeMessageHelper(msg, true , "utf-8" );
- String toList = getMailList(address);
- InternetAddress[] iaToList = new InternetAddress().parse(toList);
- msg.setRecipients(Message.RecipientType.TO,iaToList);
- helper.setFrom(from);
- helper.setSubject(subject);
- helper.setText(content, true );
- //添加内嵌文件,第1个参数为cid标识这个文件,第2个参数为资源
- helper.addInline("a" , new File( "E:/logo_a.jpg" )); //附件内容
- helper.addInline("b" , new File( "E:/logo_b.png" ));
- File file=new File( "E:/测试中文文件.rar" );
- // 这里的方法调用和插入图片是不同的,使用MimeUtility.encodeWord()来解决附件名称的中文问题
- helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
- //如果主题出现乱码,可以使用该函数,也可以使用下面的函数
- //helper.setSubject(MimeUtility.encodeText(String text,String charset,String encoding))
- //第2个参数表示字符集,第三个为目标编码格式。
- //MimeUtility.encodeWord(String word,String charset,String encoding)
- sender.send(msg);
- }
- /**
- * 集合转换字符串
- */
- 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();
- }
- //通过模板构造邮件内容,参数content将替换模板文件中的${content}标签。
- private String getMailText(String content) throws Exception {
- String htmlText = "" ;
- //通过指定模板名获取FreeMarker模板实例
- Template tpl = freeMarkerConfigurer.getConfiguration().getTemplate("registerUser.ftl" );
- Map map = new HashMap(); //FreeMarker通过Map传递动态数据
- map.put("content" ,content); //注意动态数据的key和模板标签中指定的属性相匹配
- //解析模板并替换动态数据,最终content将替换模板文件中的${content}标签。
- htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl,map);
- return htmlText;
- }
- }