springboot集成mail实现邮件服务

1,新建mailconfig类,对邮件服务固定配置进行实体封装:

import java.util.Properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;
@Configuration
public class MailConfig
{
    @Value("${spring.mail.username}")
    private String emailFrom;

    public String getEmailFrom() {
        return emailFrom;
    }

    public void setEmailFrom(String emailFrom) {
        this.emailFrom = emailFrom;
    }


    @Value("${spring.mail.host}")
    private String mailHost;
    @Value("${spring.mail.username}")
    private String mailUsername;
    @Value("${spring.mail.password}")
    private String mailPassword;
    @Value("${spring.mail.mailTemplate}")
    private String mailTemplate;
    @Value("${spring.mail.to}")
    private String to;
    @Value("${spring.mail.subject}")
    private String subject;
    @Value("${spring.mail.default-encoding}")
    private String encoding;
    @Value("${spring.mail.ccList}")
    private String ccList;

    public void setCcList(String ccList)
    {
        this.ccList = ccList;
    }

    public void setSubject(String subject)
    {
        this.subject = subject;
    }

    public void setTo(String to)
    {
        this.to = to;
    }

    public void setMailTemplate(String mailTemplate)
    {
        this.mailTemplate = mailTemplate;
    }

    public void setMailPassword(String mailPassword)
    {
        this.mailPassword = mailPassword;
    }

    public void setMailUsername(String mailUsername)
    {
        this.mailUsername = mailUsername;
    }

    public void setMailHost(String mailHost)
    {
        this.mailHost = mailHost;
    }

    public void setEncoding(String encoding)
    {
        this.encoding = encoding;
    }

    public String getMailHost()
    {
        return this.mailHost;
    }

    public String getMailUsername()
    {
        return this.mailUsername;
    }

    public String getMailPassword()
    {
        return this.mailPassword;
    }

    public String getMailTemplate()
    {
        return this.mailTemplate;
    }

    public String getTo()
    {
        return this.to;
    }

    public String getSubject()
    {
        return this.subject;
    }

    public String getEncoding()
    {
        return this.encoding;
    }

    public String getCcList()
    {
        return this.ccList;
    }

    @Bean
    public JavaMailSenderImpl mailSender()
    {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        Properties javaMailProperties = new Properties();


        sender.setJavaMailProperties(javaMailProperties);
        sender.setDefaultEncoding(this.encoding);
        sender.setHost(this.mailHost);

        sender.setUsername(this.mailUsername);
        sender.setPassword(this.mailPassword);
        return sender;
    }
}

2,在resources下的系统文件application.yml中添加如下配置:

spring:
    mail:
      host: smtp.qq.com
      username:  发件人@qq.com
      password: 授权码
      default-encoding: UTF-8
      to: 收件人@qq.com
      subject: 邮件主题
      mailTemplate: template.ftl(模板文件)
      ccList:  抄送人@qq.com

3,新建Mail类,对调用信息进行实体封装:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Mail implements Serializable {
    private static final long serialVersionUID = 1L;
    //必填参数
    private String to;//接收方邮箱
    private String subject;//主题
    private String ccList;//抄送人list//选填
    private String template;//模板
    private HashMap<String, String> kvMap;// 自定义model参数
}

 

4,定义MailService接口:

public interface MailService {
    public void sendFreemarker(Mail mail);

}

 

5,MailServiceImpl业务实现:

@Service
public class MailServiceImpl implements MailService {
    private static final Logger log = LoggerFactory.getLogger(MailServiceImpl.class);
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private MailConfig mailConfig;
    @Autowired
    private FreeMarkerConfigurer configurer;

    @Override
    public void sendFreemarker(Mail mail)
    {
        try
        {
            MimeMessage mimeMessage = this.mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            helper.setFrom(this.mailConfig.getMailUsername());
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getSubject());
            helper.setCc(mail.getCcList());
            File file = ResourceUtils.getFile("classpath:templates/report.ftl");//附件文件在resource下的相对路径
            helper.addAttachment("report.html", file);//添加附件文件

            Map<String, Object> model = new HashMap();
            model.put("ReportData", mail);//reportData为模板文件中需要渲染的数据,根据自己需要添加,此处暂时用mail代替
            try
            {
                Template template = this.configurer.getConfiguration().getTemplate(mail.getTemplate());//模板文件请自定义,内为邮件内容模板  ps:邮箱只能解析简单的html和css样式,复杂样式可能会乱码
                

                try
                {
                    String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);//获取模板文件和model数据
                    helper.setText(text, true);//添加ftl文件到邮件内容
                    this.mailSender.send(mimeMessage);//发送邮件
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        catch (MessagingException e)
        {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}

6,邮件服务单元测试:

@Listeners({AutoTestListener.class, RetryListener.class})
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@Import(TestApplication.class)
public class mailtest {

    @Test
    public void mailsendtest() {

        Mail mail=new Mail();
        mail.setTo("收件人@qq.com");
        mail.setSubject("接口自动化定时任务_测试报告");
        mail.setCcList("抄送人@qq.com");
        mail.setTemplate("report.ftl");//模板文件
        mailService.sendFreemarker(mail);
    }


}  

7,效果图如下:

 

以上就是对springboot集成mail实现邮件发送,后续使用都可以通过service注入然后进行使用或者封装啦~

 

 

posted @ 2018-12-20 16:45  蜗小稂  阅读(3083)  评论(0编辑  收藏  举报