19-Spring Email例子

该例子代码简要说明Spring通过查找和解析velocity模板,进行邮件的发送

创建邮件配置中心

/**
 * 邮件配置中心
 */
@Configuration
@ComponentScan("spittr")
@PropertySource("classpath:mail.properties")
public class MailConfig {

  //邮件发送器bean
  @Bean
  public JavaMailSenderImpl mailSender(Environment env) {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost(env.getProperty("mailserver.host"));
    mailSender.setPort(Integer.parseInt(env.getProperty("mailserver.port")));
    mailSender.setUsername(env.getProperty("mailserver.username"));
    mailSender.setPassword(env.getProperty("mailserver.password"));
    return mailSender;
  }  

  //velocity引擎bean
  @Bean
  public VelocityEngineFactoryBean velocityEngine() {
    VelocityEngineFactoryBean velocityEngine = new VelocityEngineFactoryBean();
    Properties props = new Properties();
    props.setProperty("resource.loader","class");
    props.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
    velocityEngine.setVelocityProperties(props);
    return velocityEngine;
  }
}

首先要配置一个邮件发送器bean,这个bean里面主要设置邮件发送服务器的域名端口、用户名和密码。这些配置信息是从类加载路径下的配置文件中获取的,在本例中就是mail.properties。

mailserver.host=smtp.163.com
mailserver.port=25
mailserver.username=
mailserver.password=

这里面配置的是163邮件服务器的域名和端口,用户名就是邮箱,密码是邮箱设置中的客户端授权码。需要进到邮箱设置中,在客户端授权密码功能中开启并设置授权码,然后在POP3/SMTP设置中,勾选POP3和SMTP服务。其他的邮件服务器我没试,大家有需要的话可以试试其他的。

接下来还需要配置一个velocity引擎bean,该bean主要负责查找和解析velocity模板。这个配置中,VelocityEngineFactoryBean对象主要设置一个Properties,该Properties对象配置的参数含义是,从类加载路径下查找velocity文件。

创建Velocity模板文件

<html>
<body>
<img src="cid:spitterLogo">
<h4>${spitterName} says...</h4>
<i>${spittleText}</i>
</body>
</html>

可以看到,模板文件中有三个参数,cid:spitterLogo,${spitterName},${spittleText},这三个参数在模板文件中,都以占位符的形式存在,实际发送邮件的时候,会将这三个参数,替换为相应的参数值进行邮件发送。接下来,我们来看一下邮件发送的具体代码。

创建邮件发送服务

@Component
public class SpitterMailServiceImpl implements SpitterMailService {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private VelocityEngine velocityEngine;

    @Override
    public void sendVelocityTemplateEmail(String from, String to, Spittle spittle) throws MessagingException {
        //1-创建mime消息对象
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        String spitterName = spittle.getSpitter().getFullName();
        //2-设置邮件发送方、接收方、标题
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject("New spittle from " + spitterName);
        //3-设置velocity模板中的参数
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("spitterName",spitterName);
        model.put("spittleText",spittle.getText());
        //4-将velocity模板转换成字符串
        String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "emailTemplate.vm", "UTF-8", model);
        helper.setText(emailText, true);
        //5-设置velocity模板中的图片
        ClassPathResource couponImage = new ClassPathResource("/coupon.jpg");
        helper.addInline("spitterLogo",couponImage);
        //6-发送邮件
        mailSender.send(message);
    }
}

这是邮件发送服务的实现类,接口中的代码就不再多说了。该类中注入了两个bean,mailSender负责发送邮件,velocityEngine负责查找和解析velocity模板文件。这里面有几个主要的操作,我们先来说一下第一步,创建mime消息对象。发送HTML这样的富文本邮件内容,需要使用MimeMessage,由于MimeMessage是java提供的API,相对的比较笨重,于是就有了Spring提供的相对方便易用的MimeMessageHelper。

接下来主要是通过VelocityEngineUtils把模板文件内容转换成字符串,然后调用setText方法把字符串设置为邮件内容。mergeTemplateIntoString方法中第2个参数是邮件模板文件名,它位于类加载路径下,第1个参数velocityEngine已经设置了从类加载路径下查找文件,因此它可以找到emailTemplate.vm文件。

其他的,设置参数和图片,只要能和模板文件中的参数占位符名称保持一致就可以了。另外,还要说一下的是coupon.jpg文件,它也位于类加载路径下,因此通过ClassPathResource可以找到它。通过下图项目结构可以看到,模板文件、邮件配置文件、图片,都在resource目录下,在项目运行的时候,该目录下的文件就位于类加载路径下。因此我们代码中从类加载路径查找文件的代码都能找到相应的文件。

19-Spring Email例子

到这里我们的主要配置和发送邮件的代码已经讲完了,但是这个邮件能不能发送还不知道,所以,我们还需要一个测试类。

创建邮件发送测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=MailConfig.class)
public class SpitterMailServiceTest {

  @Autowired
  private SpitterMailService mailService;

  //发送velocity模板邮件测试方法
  @Test
  public void sendVelocityTemplateEmail() throws Exception {
    Long id = 1L;
    String userName = "habuma";
    String password = null;
    String fullName = "Craig Walls";
    String email = "[email protected]";
    boolean updateByEmail = true;
    String text = "Hiya!";
    Spitter spitter = new Spitter(id, userName, password, fullName, email, updateByEmail);
    Spittle spittle = new Spittle(id, spitter, text, new Date());
    String from = "";//发送者邮件地址
    String to = "";//接收者邮件地址
    mailService.sendVelocityTemplateEmail(from, to, spittle);
    System.out.println("send success");
  }

测试方法中有Spitter和Spittle两个实体类,具体代码就不贴了,留给大家来创建吧。这个测试方法要强调一点,发送者邮件地址一定要是前面mail.properties配置文件中的邮箱地址,否则就会报错,具体原因我也不太清楚。好了,现在运行这个测试方法,就可以给别人发邮件了。

代码下载地址:https://download.****.net/download/guyu1985/10694419