美文网首页软件测试学习之路
Spring结合freemaker配置发送邮件

Spring结合freemaker配置发送邮件

作者: 乘风破浪的姐姐 | 来源:发表于2018-05-07 10:33 被阅读28次

自动化测试过程中,需要将测试结果以固定模板发送邮件的方式进行邮件发送。以下详细介绍配置过程。
1、在pom.xml文件中引入需要的包

 <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.4.7</version>
    </dependency>
    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>javax.mail-api</artifactId>
      <version>1.5.5</version>
    </dependency>
    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.23</version>
    </dependency>

2、在main/resources下新增配置文件spring-mail.xml
注意这里需要引入的配置:
1)、FreeMarker模板的配置
2)、javamail邮件发送的配置
3)、SimpleMailMessage的参数配置
4)、邮件服务实现类service的注入

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 引入mail配置文件 -->
    <context:property-placeholder location="classpath:mail.properties"/>
    <!--FreeMarker模板 -->
    <bean id="freeMarkerConfigurer"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="classpath:freemaker/" />
        <property name="freemarkerSettings">
            <props>
                <prop key="locale">zh_CN</prop>
                <prop key="default_encoding">UTF-8</prop>
            </props>
        </property>
    </bean>

    <bean id="emailService" class="com.atguigu.crud.service.EmailService" >
        <property name="mailSender" ref="mailSender"></property>
        <property name="freeMarkerConfigurer" ref="freeMarkerConfigurer"></property>
        <property name="simpleMailMessage" ref="simpleMailMessage"></property>
    </bean>
    <!--邮件发送 -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="host" value="${mail.host}" />
        <property name="username" value="${mail.username}" />
        <property name="password" value="${mail.password}" />
        <property name="javaMailProperties">
            <props>
                <prop key="classic_compatible">true</prop>
                <prop key="mail.transport.protocol">smtp</prop>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.timeout">25000</prop>
            </props>
        </property>
    </bean>

    <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
        <property name="from" value="${mail.username}" />
        <property name="subject" value="${mail.title}" />
        <property name="to" value="${mail.touser}" />
       <property name="cc" value="${mail.cc}"/>
    </bean>

</beans>

3、创建mail.properties文件,便宜上述配置中的参数化调用

mail.host=smtp.163.com
mail.username=***@163.com
mail.password=***
mail.title=error
mail.touser=***@qq.com,***@126.com
mail.cc=***@163.com

4、在项目的resources的freemaker的包下新增邮件发送模板 welcome.ftl

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf8">
</head>
<body>
恭喜您成功注册!<br/>
您的用户名为:<font color='red' size='20'>${name}</font>,
您的ID为:<font color='red' size='20'>${id}</font>  <img src='cid:welcome'/>
</body>

5、新增EmailService类,用于邮件发送处理

package com.atguigu.crud.service;

import com.atguigu.crud.bean.User;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class EmailService {
       private JavaMailSender mailSender;
       private FreeMarkerConfigurer freeMarkerConfigurer;
       private SimpleMailMessage simpleMailMessage;

       public void setMailSender(JavaMailSender mailSender) {
              this.mailSender = mailSender;
       }

       public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
              this.freeMarkerConfigurer = freeMarkerConfigurer;
       }

       public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
              this.simpleMailMessage = simpleMailMessage;
       }

       //通过freemarker模板构造邮件内容
       private String getMailText(User employee) throws IOException, TemplateException {
              // 通过指定模板名获取FreeMarker模板实例
              Template template =  freeMarkerConfigurer.getConfiguration().getTemplate("welcome.ftl");

              // FreeMarker通过Map传递动态数据
              Map<String,Object> map = new HashMap<String,Object>();
              // 注意动态数据的key和模板标签中指定的属性相匹配
              map.put("name",employee.getUsername());
              map.put("id",employee.getUserid());

              // 解析模板并替换动态数据,最终content将替换模板文件中的${content}标签。
              String htmlTxt = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
              return htmlTxt;
       }

       public void  sendMail(User employee, String filepath1, String wordPath2) throws Exception {
              MimeMessage message = mailSender.createMimeMessage();
              MimeMessageHelper helper = new MimeMessageHelper(message,true,"utf-8");
              helper.setFrom(simpleMailMessage.getFrom());
              helper.setTo(simpleMailMessage.getTo());
              helper.setCc(simpleMailMessage.getCc());
              helper.setSubject(MimeUtility.encodeText(simpleMailMessage.getSubject()));
              helper.setText(getMailText(employee),true);
              helper.addInline("welcome",new File(filepath1));
              mailSender.send(message);
              System.out.println("邮件发送成功...");

       }
}

6、上述邮件实现类中用到的User实体类内容:

package com.atguigu.crud.bean;

public class User{
    private String userid;
    private String username;
    public String getUserid() {
        return userid;
    }
    public void setUserid(String userid) {
        this.userid = userid == null ? null : userid.trim();
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

7、测试类,使用junit测试发送邮件

package com.atguigu.crud.test;
import com.atguigu.crud.bean.User;
import com.atguigu.crud.service.EmailService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class EmailSendTest {
    @Test
    public void testSendMail() throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-mail.xml");
        EmailService emailService = (EmailService) context.getBean("emailService");

        User user = new User();
        user.setUsername("sundy");
        user.setUserid("10000");
        String path1="./src/main/resources/welcome.gif";
        String path2="./src/main/resources/welcome.docx";
        emailService.sendMail(user,path1,path2);
    }
}

测试结果:


image.png

在测试过程中遇到问题:
使用javamail进行用户注册并给用户发一封邮件实现用户激活功能时,在所有代码都没有问题时仍然没有办法成功发送邮件并且提示错误com.sun.mail.smtp.SMTPSendFailedException: 554 DT:SPM 163 smtp11,D8CowAAX_C3G_FBZ1RimNQ--.35430S2 1498479815,please see http://mail.163.com/help/help_spam_16.htm?ip=119.xx.xx.xx&hostid=smtp11&time=1498479815,然后去点链接进网易查看了一下,官方给出的是【•554 DT:SPM 发送的邮件内容包含了未被许可的信息,或被系统识别为垃圾邮件。请检查是否有用户发送病毒或者垃圾邮件;】,没什么用。在网上查了很长时间,有很多都说试一下发送正常一点的内容,试了很多遍也还是报错。

解决方案:
发送给收信人之前给自己抄送一份即可。
helper.setCc(simpleMailMessage.getCc());

相关文章

网友评论

    本文标题:Spring结合freemaker配置发送邮件

    本文链接:https://www.haomeiwen.com/subject/zwolrftx.html