spring发送支持HTML邮件

1、发送Email工具类

package com.iss.itreasury.test.htmlmail;


import javax.mail.internet.MimeMessage;

import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
/**
 * -----------------------------------------
 * @文件: Email.java
 * @作者: fancy
 * @邮箱: [email protected]
 * @时间: 2012-6-12
 * @描述: 发送Email工具类
 * -----------------------------------------
 */
public class Email {
    
    private JavaMailSender javaMailSender;
    private SimpleMailMessage simpleMailMessage;
    
  /**
     * @方法名: sendMail 
     * @参数名:@param subject  邮件主题
     * @参数名:@param content 邮件主题内容
     * @参数名:@param to         收件人Email地址
     * @描述语: 发送邮件
     */
    public void sendMail(String subject, String content, String to) {
        
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
          /**
             * new MimeMessageHelper(mimeMessage,true)之true个人见解:
             * 关于true参数,官方文档是这样解释的:
             * use the true flag to indicate you need a multipart message
             * 翻译过来就是:使用true,以表明你需要多个消息
             * 再去翻一下MimeMessageHelper的API,找到这样一句话:
             * supporting alternative texts, inline elements and attachments
             * 也就是说,如果要支持内联元素(HTML)和附件就必须给定第二个参数为true
             * 否则抛出 java.lang.IllegalStateException 异常
             */
          /**
             * 刚开始收到邮件显示中文乱码,于是赶紧查看官方文档,没有提到,再查阅API,也没有查到Set编码的方法,
             * 于是就在HTML里面自己指定编码,也不起作用,邮件还是显示中文乱码;
             * 最后的结论是:如果HTML内容含有中文必须指定HTML的编码,默认是ISO-8859-1,所以会显示中文乱码
             * 在MimeMessageHelper的构造方法中找到:
             * MimeMessageHelper(MimeMessage mimeMessage, boolean multipart, String encoding)
             * 实验一下,OK,原来编码是在这儿设置,没事了,中文正常显示
             */
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
            messageHelper.setFrom(simpleMailMessage.getFrom()); //设置发件人Email
            messageHelper.setSubject(subject); //设置邮件主题
            messageHelper.setText(content);   //设置邮件主题内容
            messageHelper.setTo(to);          //设定收件人Email
            //步骤 1
            //资源的引用方法:cid:你自己设置的资源ID
            messageHelper.setText( 
            "<html>" + 
              "<body>" +
                "<BR>" +
                "<div align='center'>" +
                  "<img src='cid:imageid'/>" +
                  "<BR>" +
                  "<h4>" +
                    "返回 fancydeepin 的Blogjava:" +
                    "<a href='http://www.blogjava.net/fancydeepin/'>http://www.blogjava.net/fancydeepin/</a>" +
                  "</h4>" +
                "</div>" +
              "</body>" +
            "</html>", true);
          /**
             * ClassPathResource:很明显就是类路径资源,我这里的附件是在项目里的,所以需要用ClassPathResource
             * 如果是系统文件资源就不能用ClassPathResource,而要用FileSystemResource,例:
             * FileSystemResource file = new FileSystemResource(new File("D:/woniu.png"));
             */
          /**
             * 如果想在HTML中使用资源,必须在HTML中通过资源 ID 先引用资源,然后才来加载资源
             */
            //步骤 2
            ClassPathResource image = new ClassPathResource("images/body.png");
            messageHelper.addInline("imageid", image);
            javaMailSender.send(mimeMessage);    //发送HTML邮件
            
        } catch (Exception e) {System.out.println("异常信息:" + e);}
    }
    //Spring 依赖注入
    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
        this.simpleMailMessage = simpleMailMessage;
    }
    //Spring 依赖注入
    public void setJavaMailSender(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }
}



2、测试类
package com.iss.itreasury.test.htmlmail;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmailTest {
	 public static void main(String[] args) {
	        ApplicationContext context = new ClassPathXmlApplicationContext("emailConfig.xml");
	        Email mail = (Email)context.getBean("simpleMail");
	        mail.sendMail("Spring SMTP Mail HTML Subject", "Spring SMTP HTML Text Content", "[email protected]");
	        //mail.sendMail("标题", "内容", "收件人邮箱");
	    }
}



3、xml配置文件(emailConfig.xml放在src目下)
<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-2.5.xsd">
  
    <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <!-- 服务器 -->
        <property name="host" value="smtp.****.com" />
        <!-- 端口号 -->
        <property name="port" value="25" />
        <!-- 用户名 -->
        <property name="username" value="*****"/>
        <!--  密码   -->
        <property name="password" value="*****"/>
        <!-- SMTP服务器验证 -->
        <property name="javaMailProperties">
            <props>
               <!-- 验证身份 -->
               <prop key="mail.smtp.auth">true</prop>
           </props>
        </property>
    </bean>
    <!-- 
       目前我用过的EMAIL账号都是网易的,下面列出网易的SMTP服务器名和端口号:
       网易邮箱         SMTP服务器     SMTP端口    POP3服务器     POP3端口
       @126.com    smtp.126.com      25         pop3.126.com     110
       @163.com    smtp.163.com      25         pop3.163.com     110
       @yeah.net   smtp.yeah.net      25         pop3.yeah.net    110
     -->
    
    <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
      <!-- 发件人email -->
        <property name="from" value="*****@*****.com" />
        <!-- 
         收件人email
        <property name="to" value="******@qq.com" />
        email主题(标题)
        <property name="subject" value="Subject" />
        email主题内容
        <property name="text">
          <value>ContentText</value>
        </property>
        -->
    </bean>
    
    <bean id="simpleMail" class="com.iss.itreasury.syscore.utils.EmailUtilForHtml">
        <property name="javaMailSender" ref="javaMailSender" />
        <property name="simpleMailMessage" ref="simpleMailMessage" />
    </bean>
    
</beans>


你可能感兴趣的:(spring,html,邮件)