springboot发送邮件的实现(简单发送,带附件发送,模板发送)

今天学了springboot如何发送邮件,做了以下的内容总结,方便自己日后复习和查看!

1.pom文件maven的引入

<!-- send mail -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- thymeleaf模板引入,之前的章节已经讲过这块的使用方法了 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.properties文件的配置

这里有一个重点的内容,就是下面一会会提到的发送邮箱的账户和密码,密码并不是我们平时登录邮箱的密码,而是需要在相关的邮箱上进行一个设置,才能使用!

###########send mail################
spring.mail.host=smtp.sina.com.cn
spring.mail.username=snowvssun@sina.com
#password 这一项,并不是我们日常使用的登录密码,我们需要开启我们的认证密码(客户端授权密码)。
spring.mail.password=24fdb134f7207393
spring.mail.default-encoding=UTF-8
####thymeleaf配置,可以省略,因为都有默认的配置####
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8

以我的邮箱,新浪邮箱为例子,来给大家稍微说一下怎么设置吧!

3.发送邮件的代码Service

我把发送邮件的三个方法都写到这个service里面,你们可以根据自己的需求进行选取使用,当然了这里都是一些简单的使用,在企业中我们往往需要复杂的操作等,模板一般用的比较多,也会封装很多公用的方法,这里就不说的那么详细了,俗话说师傅引进门修行靠自己!想要拓展方法自己去拓展吧!

package com.lengmo.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Service
public class SendMailService {
    protected Logger logger = LoggerFactory.getLogger(SendMailService.class);

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String fromMail;

    /**
     *SimpleMailMessage发送简单的邮件
     * @param toAddress 接受地址
     * @param subject 主题
     * @param context 邮件内容
     */
    public void  sendSimpleMail(String toAddress ,String subject,String context){
        SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
        simpleMailMessage.setFrom(fromMail);
        simpleMailMessage.setTo(toAddress);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(context);
        try {
            javaMailSender.send(simpleMailMessage);
            logger.info("Successfully!!!!!!");
        } catch (Exception e) {
            logger.info("Filed!!!!!!"+ e);
        }
    }

    /**
     *MimeMessage发送带附件的邮件
     * @param toAddress 接受地址
     * @param subject 主题
     * @param context 邮件内容
     */
    public void sendAttchMail(String toAddress ,String subject,String context){
        try {
            MimeMessage mimeMessage=javaMailSender.createMimeMessage();
            //下面的这个方法很重要啊,如果需要加附件传递,记得开启multipart为true
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(fromMail);
            helper.setTo(toAddress);
            helper.setSubject(subject);
            helper.setText(context);

            //添加附件
            String filePath = "E:\\helloworld.txt";
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            javaMailSender.send(mimeMessage);
            logger.info("Successfully!!!!!!");
        } catch (Exception e) {
            logger.info("Filed!!!!!!"+ e);
        }

    }

    /**
     *sendThymeleafMail以模板的形式发送邮件并带附件
     * @param toAddress 接受地址
     * @param subject 主题
     * @param context 邮件内容
     */
    public void sendThymeleafMail(String toAddress ,String subject,String context){
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(fromMail);
            helper.setTo(toAddress);
            helper.setSubject(subject);

            Context conThyme = new Context();
            Map<String, Object> hashMap = new HashMap<String, Object>();
            hashMap.put("id", 214);
            hashMap.put("code", "DYA12R");
            conThyme.setVariables(hashMap);
            String emailContext = templateEngine.process("emailTest", conThyme);
            helper.setText(emailContext, true);

            //添加附件
            String filePath = "E:\\helloworld.txt";
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);

            javaMailSender.send(message);
            logger.info("Successfully!!!!!!");
        } catch (MessagingException e) {
            logger.info("Filed!!!!!!"+ e);
        }
    }
}

4.老规矩,代码验证

package com.lengmo.controller;

import com.lengmo.service.ApacheHtmlEmailService;
import com.lengmo.service.SendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/mail")
public class SendMailController {

    @Autowired
    private SendMailService sendMailService;
    @Autowired
    private ApacheHtmlEmailService apacheHtmlEmailService;

    @RequestMapping("/send")
    public  void sendMail(){
        //sendMailService.sendSimpleMail("591507760@qq.com","我是简单的发送","sendSimpleMail  hellow  world");
        //sendMailService.sendAttchMail("591507760@qq.com","我带附件","sendAttchMail  hellow  world");
        sendMailService.sendThymeleafMail("591507760@qq.com","我模板并带附件","sendThymeleafMail  hellow  world");

       // apacheHtmlEmailService.sendSimpleMailByHtmlEmail("591507760@qq.com","我是简单的发送","sendSimpleMailByHtmlEmail hellow world");
    }
}

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值