基于SpringBoot实现邮件发送

描述

应用场景

发送邮件验证码等,定时发送、同时发送多封邮件等。

功能简介

本项目通过Springboot发送email邮件,包括普通文本邮件 、HTML内容板式邮件 、包含静态资源邮件以及带附件邮件等。

一封邮件同时发送多人、异步多线程发送邮件、定时发送邮件等场景功能。

项目说明

核心Maven依赖

   

    org.springframework.boot

    spring-boot-starter-mail

   

核心配置

如果是服务邮箱配置类似

#QQ邮箱服务主机地址 
spring.mail.host=smtp.qq.com 

#邮箱账号 
spring.mail.username=2389323369@qq.com

 #邮箱授权码 
spring.mail.password=qtglycyclomqgci

#右键默认编码 
spring.mail.default-encoding=UTF-8

 

spring.mail.username=2289523269@qq.com

 ----需要修改成自己的邮箱账号(发送方邮箱) #邮箱授权码

spring.mail.password=qtglycyclomqgci 

----需要修改成自己的邮箱授权码(下面会介绍如何获取)

QQ邮箱授权码获取

如果授权码不正确会报错误

org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 535 Login Fail. Please enter your authorization code to login. More information in http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256

at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:439)

at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:322)

at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:311)

at com.example.demo.service.impl.MailServiceImpl.sendSimpleMail(MailServiceImpl.java:38)

1、什么是授权码? 

授权码是QQ邮箱推出的,用于登录第三方客户端的专用密码。适用于登录以下服务:POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务。温馨提醒:为了你的帐户安全,更改QQ密码以及独立密码会触发授权码过期,需要重新获取新的授权码登录。

2、怎么获取授权码? 

进入QQ邮箱主页-->设置-->帐户-->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务: 

 

邮件

点击“开启”-->验证密保-->获取授权码: 

 

邮件

核心代码

@Service
public class MailServiceImpl implements MailService {

    /**
     * 日志
     */
  private static final org.slf4j.Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

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

    //用于发送文件
    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void checkMail(EmailModel emailModel) {
        Assert.notNull(emailModel,"邮件模板不能为空");
        Assert.notNull(emailModel.getEmail(), "邮件收件人不能为空");
        Assert.notNull(emailModel.getSubject(), "邮件主题不能为空");
        Assert.notNull(emailModel.getContent(), "邮件内容不能为空");
    }

    @Async("EmailAsync")
    @Override
    public Boolean sendSimpleMail(EmailModel emailModel) {
      try {
          SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);//发信人
            message.setTo(emailModel.getEmail().split(";"));//邮件收件人 1或多个 以";"隔开
          message.setSubject(emailModel.getSubject());//主题
          message.setText(emailModel.getContent());//内容

          mailSender.send(message);

            logger.info("发送文本邮件成功");
      } catch (Exception e) {
        e.printStackTrace();
        logger.error("发送文本邮件失败");
        return false;
      }
      return true;
    }

    @Async("EmailAsync")
    @Override
    public Boolean sendHtmlMail(EmailModel emailModel) {
        String to = emailModel.getEmail();
        String subject = emailModel.getSubject();
        String content = emailModel.getContent();
        logger.info("发送HTML邮件开始:{},{},{}", to, subject, content);
        //使用MimeMessage,MIME协议
        MimeMessage message = mailSender.createMimeMessage();
        
        MimeMessageHelper helper;
        //MimeMessageHelper帮助我们设置更丰富的内容
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to.split(";"));
            helper.setSubject(subject);
            helper.setText(content, true);//true代表支持html
            mailSender.send(message);
            logger.info("发送HTML邮件成功");
        } catch (MessagingException e) {
            logger.error("发送HTML邮件失败:", e);
            return false;
        }
        return true;
    }

    @Async("EmailAsync")
    @Override
    public Boolean sendAttachMentMail(EmailModel emailModel) {
        String to = emailModel.getEmail();
        String subject = emailModel.getSubject();
        String content = emailModel.getContent();
        String filePath = emailModel.getAttachFilePath();
        logger.info("发送附件邮件开始:{},{},{},{}", to, subject, content, filePath);
        MimeMessage message = mailSender.createMimeMessage();
    
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            //true代表支持多组件,如附件,图片等
            helper.setFrom(from);
            helper.setTo(to.split(";"));
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);//添加附件,可多次调用该方法添加多个附件
            mailSender.send(message);
            logger.info("发送附件邮件成功");
            } catch (MessagingException e) {
                logger.error("发送附件邮件失败", e);
                return false;
        }
            return true;
    }

    @Async("EmailAsync")
    @Override
    public Boolean sendInlineResourceMail(EmailModel emailModel) {
        String to = emailModel.getEmail();
        String subject = emailModel.getSubject();
        String content = emailModel.getContent();
        String resourcePath = emailModel.getResourcePath();
        String resourceName = emailModel.getResourceName();
        logger.info("发送带图片邮件开始:{},{},{},{},{}", to, subject, content, resourcePath, resourceName);
        MimeMessage message = mailSender.createMimeMessage();
        
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to.split(";"));
            helper.setSubject(subject);
            helper.setText(content, true);
            // 以绝对路径的方式读取文件
            FileSystemResource res = new FileSystemResource(new File(resourcePath));
            helper.addInline(resourceName, res);//重复使用添加多个图片
            mailSender.send(message);
            logger.info("发送带图片邮件成功");
        } catch (MessagingException e) {
            logger.error("发送带图片邮件失败", e);
            return false;
        }
        return true;
    }

    @Async("EmailAsync")
    @Override
    public Boolean sendHtmlImageMail(EmailModel emailModel) {
        String to = emailModel.getEmail();
        String subject = emailModel.getSubject();
        String content = emailModel.getContent();
        String resourcePath = emailModel.getResourcePath();
        logger.info("发送带图片邮件开始:{},{},{},{}", to, subject, content, resourcePath);
        MimeMessage message = mailSender.createMimeMessage();
    
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to.split(";"));
            helper.setSubject(subject);
            helper.setText(content, true);
            // cid是固定写法
            helper.setText(
                "

hello world!

" + "", true); FileSystemResource img = new FileSystemResource(new File(resourcePath)); helper.addInline("aaa", img); mailSender.send(message); logger.info("发送带图片邮件成功"); return true; } catch (MessagingException e) { logger.error("发送带图片邮件失败", e); return false; } } }

源码下载地址获取

关注微信公众号“Java烂笔头”,回复“邮件

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分