springboot 整合邮件服务

加入maven 依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
</dependency>


配置文件

# 邮箱服务器地址
spring.mail.host=smtp.qq.com
spring.mail.port=465
#用户名
spring.mail.username=xxxxx@qq.com
#密码
spring.mail.password=mebaqizkkzjcqgfbe
spring.mail.default-encoding=UTF-8

spring.mail.properties.smtp.auth=true
spring.mail.properties.smtp.starttls.enable=true
spring.mail.properties.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enable=true

具体代码 Service:

@Component
public class MailServiceImpl implements MailService{

    private static  final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${mail.fromMail.addr}")
    private String from;

    /**
     * 简单邮箱
     *
     * @Author: wpf
     * @Date: 15:09 2018/6/13
     * @Description: 
     * @param  * @param null  
     * @return   
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
       // message.setCc(C);// 抄送者
        message.setSubject(subject);
        message.setText(content);

        try {
            mailSender.send(message);
            logger.info("简单邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送简单邮件时发生异常!", e);
        }

    }

    /**
     * html格式邮件
     *
     * @Author: wpf
     * @Date: 15:09 2018/6/13
     * @Description: 
     * @param  * @param null  
     * @return   
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
            logger.info("html邮件发送成功");
        } catch (MessagingException e) {
            logger.error("发送html邮件时发生异常!", e);
        }
    }

    /**
     * 带附件的html邮件
     *
     * @Author: wpf
     * @Date: 15:18 2018/6/13
     * @Description: 
     * @param  * @param null  
     * @return   
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);

            mailSender.send(message);
            logger.info("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送带附件的邮件时发生异常!", e);
        }
    }

    /**
     * 带多个附件的html邮件
     *
     * @Author: wpf
     * @Date: 15:18 2018/6/13
     * @Description:
     * @param  * @param null
     * @return
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String[] filePathList){
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            for(String filePath: filePathList){
                FileSystemResource file = new FileSystemResource(new File(filePath));
                String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
                helper.addAttachment(fileName, file);
            }

            mailSender.send(message);
            logger.info("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送带附件的邮件时发生异常!", e);
        }
    }

    /**
     * 带静态资源的邮件
     *
     * @Author: wpf
     * @Date: 15:25 2018/6/13
     * @Description: 
     * @param  * @param null  
     * @return   
     */
    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);

            mailSender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送嵌入静态资源的邮件时发生异常!", e);
        }
    }

    /**
     * 带多个静态资源的邮件
     *
     * @Author: wpf
     * @Date: 15:41 2018/6/13
     * @Description: 
     * @param  * @param null  
     * @return   
     */
    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String[] rscPathList, String[] rscIdList) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            for (int i=0; i < rscIdList.length; i++){

                String rscPath = rscPathList[i];
                String rscId = rscIdList[i];
                logger.info(rscPath);
                logger.info(rscId);
                FileSystemResource res = new FileSystemResource(new File(rscPath));
                helper.addInline(rscId, res);
                logger.info(rscId);
                logger.info(res.toString());
            }


            mailSender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送嵌入静态资源的邮件时发生异常!", e);
        }
    }


}

controller:

@RestController
@RequestMapping("/")
public class TestController {

    final static Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private MailService mailService;
    @Autowired
    private TemplateEngine templateEngine;

    @GetMapping("/hello")
    public String hello(){

        mailService.sendSimpleMail("3354371617@qq.com","test simple mail"," hello this is simple mail");
        return "ok";
    }

    @GetMapping("/testHtmlMail")
    public String testHtmlMail() throws Exception {
        String content="<html>\n" +
                "<body>\n" +
                "    <p>hello world ! 这是一封Html邮件!</p>\n" +
                "</body>\n" +
                "</html>";
        mailService.sendHtmlMail("3354371617@qq.com","test simple mail",content);

        return "ok";
    }

    @GetMapping("/testHtmlMail1")
    public String testHtmlMail1() throws Exception {
        String content="<html>\n" +
                "<body>\n" +
                "    <p>hello world ! 这是一封Html邮件!</p>\n" +
                "</body>\n" +
                "</html>";
        String filePath = "F:\\1\\test\\tes\\ne.txt";
        mailService.sendAttachmentsMail("3354371617@qq.com","test simple mail",content, filePath);

        return "ok";
    }

    @GetMapping("/testHtmlMail2")
    public String testHtmlMail2() throws Exception {
        String content="<html>\n" +
                "<body>\n" +
                "    <p>hello world ! 这是一封Html邮件!</p>\n" +
                "</body>\n" +
                "</html>";
        String[] filePathList = {"F:\\1\\test\\tes\\ne.txt","F:\\1\\test\\tes\\Test.java"};
        mailService.sendAttachmentsMail("3354371617@qq.com","test simple mail",content,filePathList);

        return "ok";
    }

    @GetMapping("/testHtmlMail3")
    public String testHtmlMail3() throws Exception {
        String rscId = "wpf";
        String content="<html><body>这是有图片的邮件:<img src=\'cid:" + rscId + "\' ></body></html>";
        String imgPath = "F:\\1\\test\\tes\\222.png";

        mailService.sendInlineResourceMail("3354371617@qq.com", "主题:这是有图片的邮件", content, imgPath, rscId);
        return "ok";
    }

    @GetMapping("/testHtmlMail4")
    public String testHtmlMail4() throws Exception {
        String[] rscIdList = {"wpf01","wpf02"};
        String content="<html><body>这是有图片的邮件:<img src='cid:" + rscIdList[0] + "' >" +
                "<img src='cid:" + rscIdList[1] + "' ></body></html>";
        String[] imgPathList = {"F:\\1\\test\\tes\\123.jpg","F:\\1\\test\\tes\\12233.jpg"};

        mailService.sendInlineResourceMail("3354371617@qq.com", "主题:这是有图片的邮件", content, imgPathList, rscIdList);
        return "ok";
    }


    /**
     * 模板邮件
     *
     * @Author: wpf
     * @Date: 16:13 2018/6/13
     * @Description: 
     * @param  * @param null  
     * @return   
     */
    @GetMapping("/testHtmlMail5")
    public String testHtmlMail5() throws Exception {

        //创建邮件正文
        Context context = new Context();
        context.setVariable("id", "wpf");
        String emailContent = templateEngine.process("emailTemplate", context);

        mailService.sendHtmlMail("3354371617@qq.com","主题:这是模板邮件",emailContent);

        return "ok";
    }

    @GetMapping("/hello1")
    public void hello1(){

        logger.info("-----------  start ---------------");

        logger.debug("aaa-===============================");
        //制造一个运行时异常,这里没有捕获
        int x = 1/0;
    }


}
源码: https://github.com/gcWpengfei/spring-cloud-rsa-aes-demo/tree/master/aes-rsa-email
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值