美文网首页
使用SpringBoot发送邮件

使用SpringBoot发送邮件

作者: sT丶 | 来源:发表于2017-08-17 14:34 被阅读0次

    前言

    在项目中可能会碰到发送邮件的需求,这时,我们就可以使用SpringBoot的mail模块进行快速的开发。

    配置

    首先,引入相关依赖

      <!--邮件模块-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
    

    然后,在application.properties中 配置如下

    #配置邮件服务
    spring.mail.host=smtp.qq.com
    spring.mail.username=xxxxxx@qq.com
    spring.mail.password=123456
    # 设置是否需要认证,如果为true,那么用户名和密码就必须的,
    #如果设置false,可以不设置用户名和密码,当然也得看你的对接的平台是否支持无密码进行访问的。
    spring.mail.properties.mail.smtp.auth=true
    # STARTTLS[1]  是对纯文本通信协议的扩展。它提供一种方式将纯文本连接升级为加密连接(TLS或SSL),而不是另外使用一个端口作加密通信。
    spring.mail.properties.mail.smtp.starttls.enable=true
    spring.mail.properties.mail.smtp.starttls.required=true
    

    在上面如果是使用QQ邮箱的话,需要现在QQ邮箱中开启SMTP服务

    image.png

    拉到最先选择开启,然后发送验证短信,发送完成即可获取授权码,这时,把授权码,写入上面配置文件的password即可。


    image.png

    至此,已经完成了相关配置。

    编写util类

    其实本身spring mail本身已经对java.util.mail做了封装,我们这里可以再次做一个简单封装以适应项目开发。
    新建MailUtil 类

    package com.jtkjbike.monitor.util;
    
    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 javax.mail.MessagingException;
    import javax.mail.internet.MimeMessage;
    import java.io.File;
    
    /**
     *
     */
    @Service
    public class MailUtil {
        private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
        @Autowired
        private JavaMailSender sender;
    
        @Value("${spring.mail.username}")
        private String from;
    
        /**
         * 发送纯文本的简单邮件
         * @param to
         * @param subject
         * @param content
         */
        public void sendSimpleMail(String to, String subject, String content){
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
    
            try {
                sender.send(message);
                logger.info("简单邮件已经发送。");
            } catch (Exception e) {
                logger.error("发送简单邮件时发生异常!", e);
            }
        }
    
        /**
         * 发送html格式的邮件
         * @param to
         * @param subject
         * @param content
         */
        public void sendHtmlMail(String to, String subject, String content){
            MimeMessage message = sender.createMimeMessage();
    
            try {
                //true表示需要创建一个multipart message
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(from);
                helper.setTo(to);
                helper.setSubject(subject);
                helper.setText(content, true);
    
                sender.send(message);
                logger.info("html邮件已经发送。");
            } catch (MessagingException e) {
                logger.error("发送html邮件时发生异常!", e);
            }
        }
    
        /**
         * 发送带附件的邮件
         * @param to
         * @param subject
         * @param content
         * @param filePath
         */
        public void sendAttachmentsMail(String to, String subject, String content, String filePath){
            MimeMessage message = sender.createMimeMessage();
    
            try {
                //true表示需要创建一个multipart message
                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);
    
                sender.send(message);
                logger.info("带附件的邮件已经发送。");
            } catch (MessagingException e) {
                logger.error("发送带附件的邮件时发生异常!", e);
            }
        }
    
        /**
         * 发送嵌入静态资源(一般是图片)的邮件
         * @param to
         * @param subject
         * @param content 邮件内容,需要包括一个静态资源的id,比如:<img src=\"cid:rscId01\" >
         * @param rscPath 静态资源路径和文件名
         * @param rscId 静态资源id
         */
        public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
            MimeMessage message = sender.createMimeMessage();
    
            try {
                //true表示需要创建一个multipart message
                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);
    
                sender.send(message);
                logger.info("嵌入静态资源的邮件已经发送。");
            } catch (MessagingException e) {
                logger.error("发送嵌入静态资源的邮件时发生异常!", e);
            }
        }
    }
    

    测试

    编写测试方法

    package com.jtkjbike.monitor.util;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    /**
     *
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class MailUtilTest {
        @Autowired
        MailUtil mailUtil;
    
        private String to = "xxxxxx@126.com";
    
        @Test
        public void testSend(){
            mailUtil.sendSimpleMail(to,"主题:测试","hhhhhhhh");
        }
    }
    
    image.png

    此时我们登录测试邮箱查看,已经成功收到了邮件。


    image.png

    参考:http://blog.csdn.net/linxingliang/article/details/52324987
    http://www.cnblogs.com/muliu/p/6017622.html
    http://blog.csdn.net/caimengyuan/article/details/51224269
    http://blog.csdn.net/clementad/article/details/51833416

    相关文章

      网友评论

          本文标题:使用SpringBoot发送邮件

          本文链接:https://www.haomeiwen.com/subject/uqagrxtx.html