SpringBoot2.3.4整合JavaMail实现发送邮件

概述

在实际开发中,经常会涉及到发送邮件的需求,比如用户激活。Spring中提供了javamail库用于发送电子邮件,发送电子邮件的主接口是MailSender,用于发送普通邮件,继承于它的JavaMailSender接口用于发送复杂的邮件,JavaMailSender还提供了一个回调接口MimeMessagePreparator用于准备MimeMessage。Spring中提供了三种发送普通邮件的方式,本文都做了代码实现。更多详情请查阅spring官网中关于邮件的描述spring-framework官网

技术栈

SpringBoot2.3.4
Freemarker
lombok

获取邮箱授权码

以QQ邮箱为例
登录QQ,进入邮箱,点击设置
SpringBoot2.3.4整合JavaMail实现发送邮件_第1张图片
点击账户,进入授权界面
SpringBoot2.3.4整合JavaMail实现发送邮件_第2张图片
下拉页面,找到授权部分,开启授权服务
SpringBoot2.3.4整合JavaMail实现发送邮件_第3张图片
根据要求发送短信获取授权码
SpringBoot2.3.4整合JavaMail实现发送邮件_第4张图片
发送短信后,点击“我已发送”,获取授权码
SpringBoot2.3.4整合JavaMail实现发送邮件_第5张图片

SpringBoot整合mail

pom.xml文件中引入依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-mailartifactId>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-freemarkerartifactId>
dependency>

application.yml文件中添加配置信息

server:
  port: 8108
spring:
  application:
    name: springboot-email
  mail:
    username: [email protected] #邮箱
    password: xxxxxxxxxxxxxx #授权码
    host: smtp.qq.com #邮箱类型
    protocol: smtp #发送邮件协议
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          ssl:
            enable: true #开启SSL
          auth: true
          port: 465
          starttls:
            enable: true
            required: true
freemarker:
  cache: false #关闭缓存
  suffix: .html #模板后缀 默认ftl
  charset: UTF-8 #文件编码
  template-loader-path: classpath:/templates/ #模板文件存放路径

业务接口实现

@Service
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.host}")
    private String host;
    @Autowired
    private MailSender mailSender;
    @Autowired
    private JavaMailSender javaMailSender;
    @Resource
    private JavaMailSenderImpl javaMailSenderImpl;
    @Autowired
    private FreeMarkerConfig freeMarkerConfig;

    /**
     * 使用MailSender发送简单邮件
     * @param mail 对方邮件地址
     * @param subject 主题
     * @param text 内容
     */
    @Override
    public boolean sendSimpleMail(String mail, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(username);
        message.setTo(mail);
        message.setSubject(subject);
        message.setText(text);
        try {
            mailSender.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 使用JavaMailSender发送简单邮件
     * @param mail 对方邮件地址
     * @param subject 主题
     * @param text 内容
     */
    @Override
    public boolean sendSimpleMailForJava(String mail, String subject, String text) {
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(mail));
                mimeMessage.setFrom(new InternetAddress(username));
                mimeMessage.setSubject(subject);
                mimeMessage.setText(text);
            }
        };
        try {
            javaMailSender.send(preparator);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 使用JavaMailSenderImpl发送邮件
     * @param mail 对方邮件地址
     * @param subject 主题
     * @param text 内容
     */
    @Override
    public boolean sendSimpleMailForJavaAndHelper(String mail, String subject, String text) {
        javaMailSenderImpl.setHost(host);
        MimeMessage message = javaMailSenderImpl.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        try {
            helper.setFrom(username);
            helper.setTo(mail);
            helper.setSubject(subject);
            helper.setText(text);
            javaMailSenderImpl.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 发送带附件邮件
     * @param mail 对方邮箱
     * @param subject 主题
     * @param text 内容
     * @param filePath 文件路径
     */
    @Override
    public boolean sendAttachmentMail(String mail, String subject, String text, String filePath) {
        javaMailSenderImpl.setHost(host);
        MimeMessage message = javaMailSenderImpl.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(username);
            helper.setTo(mail);
            helper.setSubject(subject);
            helper.setText(text, true);
            FileSystemResource resource = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
            helper.addAttachment(fileName, resource);
            javaMailSenderImpl.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 发送html图片邮件
     * @param mail 对方邮箱
     * @param subject 主题
     * @param text 内容
     * @param filePath 文件路径
     * @return
     */
    @Override
    public boolean sendHtmlPictureMail(String mail, String subject, String text, String filePath) {
        javaMailSenderImpl.setHost(host);
        MimeMessage message = javaMailSenderImpl.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(username);
            helper.setTo(mail);
            helper.setSubject(subject);
            FileSystemResource resource = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
            helper.setText("", true);
            helper.addInline(fileName, resource);
            javaMailSenderImpl.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 发送html邮件
     * @param mail 对方邮件地址
     * @param subject 主题
     * @param text 内容
     * @return
     */
    @Override
    public boolean sendHtmlMail(String mail, String subject, String text) {
        javaMailSenderImpl.setHost(host);
        MimeMessage message = javaMailSenderImpl.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(username);
            helper.setTo(mail);
            helper.setSubject(subject);
            helper.setText(text, true);
            javaMailSenderImpl.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 发送模板邮件
     * @param mail 对方邮件地址
     * @param subject 主题
     * @param template 模板名称
     * @return
     */
    @Override
    public boolean sendTemplateMail(String mail, String subject, String template) {
        try {
            Template temp = freeMarkerConfig.getConfiguration().getTemplate(template);
            Map<String, Object> map = new HashMap<>();
            map.put("username", mail);
            String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(temp, map);
            this.sendHtmlMail(mail, subject, templateHtml);
            return true;
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}

邮件发送

@RestController
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private EmailService emailService;

    /**
     * 使用MailSender发送简单邮件
     * @param email
     */
    @PostMapping("/sendSimpleMail")
    public ResultData sendSimpleMail(@RequestBody Email email) {
        boolean flag = emailService.sendSimpleMail(email.getMail(), email.getSubject(), email.getText());
        if (flag) {
            return ResultData.ok().message("邮件发送成功!");
        } else {
            return ResultData.error().message("邮件发送失败!");
        }
    }

    /**
     * 使用JavaMailSender发送简单邮件
     * @param email
     */
    @PostMapping("/sendSimpleMailForJava")
    public ResultData sendSimpleMailForJava(@RequestBody Email email) {
        boolean flag = emailService.sendSimpleMailForJava(email.getMail(), email.getSubject(), email.getText());
        if (flag) {
            return ResultData.ok().message("邮件发送成功!");
        } else {
            return ResultData.error().message("邮件发送失败!");
        }
    }

    /**
     * 使用JavaMailSenderImpl发送邮件
     * @param email
     */
    @PostMapping("/sendSimpleMailForJavaAndHelper")
    public ResultData sendSimpleMailForJavaAndHelper(@RequestBody Email email) {
        boolean flag = emailService.sendSimpleMailForJavaAndHelper(email.getMail(), email.getSubject(), email.getText());
        if (flag) {
            return ResultData.ok().message("邮件发送成功!");
        } else {
            return ResultData.error().message("邮件发送失败!");
        }
    }

    /**
     * 发送带附件邮件
     * @param email
     * @return
     */
    @PostMapping("/sendAttachmentMail")
    public ResultData sendAttachmentMail(@RequestBody Email email) {
        boolean flag = emailService.sendAttachmentMail(email.getMail(), email.getSubject(), email.getText(), email.getFilePath());
        if (flag) {
            return ResultData.ok().message("发送带附件邮件成功!");
        } else {
            return ResultData.error().message("发送带附件邮件失败!");
        }
    }

    /**
     * 发送html图片邮件
     * @param email
     * @return
     */
    @PostMapping("/sendHtmlPictureMail")
    public ResultData sendHtmlPictureMail(@RequestBody Email email) {
        boolean flag = emailService.sendHtmlPictureMail(email.getMail(), email.getSubject(), email.getText(), email.getFilePath());
        if (flag) {
            return ResultData.ok().message("发送HTML图片邮件成功!");
        } else {
            return ResultData.error().message("发送HTML图片邮件失败!");
        }
    }

    /**
     * 发送html邮件
     * @param email
     * @return
     */
    @PostMapping("/sendHtmlMail")
    public ResultData sendHtmlMail(@RequestBody Email email) {
        boolean flag = emailService.sendHtmlMail(email.getMail(), email.getSubject(), email.getText());
        if (flag) {
            return ResultData.ok().message("发送HTML邮件成功!");
        } else {
            return ResultData.error().message("发送HTML邮件失败!");
        }
    }

    /**
     * 发送html模板邮件
     * @param email
     * @return
     */
    @PostMapping("/sendTemplateMail")
    public ResultData sendTemplateMail(@RequestBody Email email) {
        boolean flag = emailService.sendTemplateMail(email.getMail(), email.getSubject(), email.getTemplate());
        if (flag) {
            return ResultData.ok().message("发送模板邮件成功!");
        } else {
            return ResultData.error().message("发送模板邮件失败!");
        }
    }
}

测试

使用postman工具测试邮件发送
测试发送简单邮件,输入地址localhost:8108/email/sendSimpleMail,选择post请求方式
SpringBoot2.3.4整合JavaMail实现发送邮件_第6张图片
测试发送html邮件,输入地址localhost:8108/email/sendHtmlMail,选择post请求方式
SpringBoot2.3.4整合JavaMail实现发送邮件_第7张图片
测试发送html图片邮件,输入地址localhost:8108/email/sendHtmlPictureMail,选择post请求方式
SpringBoot2.3.4整合JavaMail实现发送邮件_第8张图片
测试发送附件邮件,输入地址localhost:8108/email/sendAttachmentMail,选择post请求方式
SpringBoot2.3.4整合JavaMail实现发送邮件_第9张图片
测试发送模板邮件,输入地址localhost:8108/email/sendTemplateMail,选择post请求方式
SpringBoot2.3.4整合JavaMail实现发送邮件_第10张图片
查看收件邮箱,核查是否收到测试发送的邮件
SpringBoot2.3.4整合JavaMail实现发送邮件_第11张图片
由于本人知识有限,文中难免会存在错误和不足,还请大家多多指正,如果有疑问,欢迎在评论区留言;如果觉得本文对你有帮助,多谢点赞!
完整代码详见码云

你可能感兴趣的:(SpringBoot,spring,boot,javamail)