springboot(九)mail发送邮件

x33g5p2x  于2021-12-17 转载在 其他  
字(10.7k)|赞(0)|评价(0)|浏览(407)

前言:

      SpringBoot实现邮件功能是非常的方便快捷的,因为SpringBoot默认有starter实现了Mail。 发送邮件应该是网站的必备功能之一,什么注册验证,忘记密码或者是给用户发送营销信息。 最早期的时候我们会使用JavaMail相关api来写发送邮件的相关代码,后来spring退出了 JavaMailSender更加简化了邮件发送的过程,在之后springboot对此进行了封装就有了 现在的spring-boot-starter-mail

新建项目:springboot-mail:

   打开pom.xml,添加以下依赖:

<dependencies>
		<!--mail-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!--lombok-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.22</version>
		</dependency>
		<!--freemarker-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>
	</dependencies>

编辑配置文件:application.properties

# JavaMailSender 邮件发送的配置
spring.mail.host=smtp.qq.com
spring.mail.username=邮箱账号
#QQ邮箱的授权码
spring.mail.password=授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.default-encoding=UTF-8

#spring.mail.host=smtp.163.com
#spring.mail.username=用户163邮箱
#spring.mail.password=邮箱密码
#spring.mail.properties.mail.smtp.auth=true
#spring.mail.properties.mail.smtp.starttls.enable=true
#spring.mail.properties.mail.smtp.starttls.required=true
#spring.mail.default-encoding=UTF-8

授权码获取:开启POP3/SMTP服务  

     登陆qq邮箱 -->设置-->账户-->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务-->POP3/SMTP服务   设置开启

新建MailBean.java

@Data
public class MailBean implements Serializable {
    //邮件发件人
    private String senderUser;
    //邮件接收人 可以同时发送多个人
    private String[] toUsers;
    //邮件抄送人 可以同时发送多个人
    private String[] ccUsers;
    //邮件密抄送人 可以同时发送多个人
    private String[] bccUsers;
    //邮件主题
    private String subject;
    //邮件内容
    private String content;
    //发送带文件的文件路径
    private String fileUrl;
    //附件名
    private String attachmentFilename;
    //发送静态资源文件中涉及<img>标签中的cid对应的contentId值
    private String contentId;
    //ftl文件名,默认配置为templates文件下的ftl文件
    private String ftlName;

}

      别看这么多,其实我们用得到哪些对应设置值就可以了。

新建:MailUtil.java

@Component
public class MailUtil {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private Configuration configuration;

    private Logger logger = LoggerFactory.getLogger(MailUtil.class);

    /**
     * 发送简单格式的邮件
     * @param mailBean
     */
    public void sendSimpleMail(MailBean mailBean) {
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            //邮件发送人
            simpleMailMessage.setFrom(mailBean.getSenderUser());
            //邮件接收人
            simpleMailMessage.setTo(mailBean.getToUsers());
            if(!StringUtils.isEmpty(mailBean.getCcUsers())){
                //抄送人,使用Cc还是Bcc大家根据具体场景自己选择
                simpleMailMessage.setCc(mailBean.getCcUsers());

            }
            if(!StringUtils.isEmpty(mailBean.getBccUsers())){
                //秘密抄送(发件人,收件人,抄送人都不会看到抄送给谁了)
                simpleMailMessage.setBcc(mailBean.getBccUsers());
            }
            //邮件主题
            simpleMailMessage.setSubject(mailBean.getSubject());
            //邮件内容
            simpleMailMessage.setText(mailBean.getContent());

            javaMailSender.send(simpleMailMessage);
        } catch (Exception e) {
            logger.error("发送失败", e.getMessage());
        }
    }

    /**
     * 发送HTML格式的邮件
     * @param mailBean
     */
    public void sendHTMLMail(MailBean mailBean) {
        try {
            MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            //发送者
            mimeMessageHelper.setFrom(mailBean.getSenderUser());
            //接收者
            mimeMessageHelper.setTo(mailBean.getToUsers());
            if(!StringUtils.isEmpty(mailBean.getCcUsers())){
                //抄送人,使用Cc还是Bcc大家根据具体场景自己选择
                mimeMessageHelper.setCc(mailBean.getCcUsers());

            }
            if(!StringUtils.isEmpty(mailBean.getBccUsers())){
                //秘密抄送(发件人,收件人,抄送人都不会看到抄送给谁了)
                mimeMessageHelper.setBcc(mailBean.getBccUsers());
            }
            mimeMessageHelper.setSubject(mailBean.getSubject());
            mimeMessageHelper.setText(mailBean.getContent(), true);
            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            System.out.println("发送失败:"+ e.getMessage());
        }
    }

    /**
     * 发送带附件格式的邮件
     * @param mailBean
     */
    public void sendAttachmentMail(MailBean mailBean) {
        try {
            MimeMessage mimeMailMessage  = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            //发送者
            mimeMessageHelper.setFrom(mailBean.getSenderUser());
            //接收者
            mimeMessageHelper.setTo(mailBean.getToUsers());
            if(!StringUtils.isEmpty(mailBean.getCcUsers())){
                //抄送人,使用Cc还是Bcc大家根据具体场景自己选择
                mimeMessageHelper.setCc(mailBean.getCcUsers());

            }
            if(!StringUtils.isEmpty(mailBean.getBccUsers())){
                //秘密抄送(发件人,收件人,抄送人都不会看到抄送给谁了)
                mimeMessageHelper.setBcc(mailBean.getBccUsers());
            }
            mimeMessageHelper.setSubject(mailBean.getSubject());
            mimeMessageHelper.setText(mailBean.getContent());
            //文件路径
            FileSystemResource file = new FileSystemResource(new File(mailBean.getFileUrl()));
            mimeMessageHelper.addAttachment(mailBean.getAttachmentFilename(), file);

            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            System.out.println("发送失败:"+e.getMessage());
        }
    }

    /**
     * 发送带静态资源的邮件
     * @param mailBean
     */
    public void sendInlineMail(MailBean mailBean) {
        try {
            MimeMessage mimeMailMessage  = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            //发送者
            mimeMessageHelper.setFrom(mailBean.getSenderUser());
            //接收者
            mimeMessageHelper.setTo(mailBean.getToUsers());
            if(!StringUtils.isEmpty(mailBean.getCcUsers())){
                //抄送人,使用Cc还是Bcc大家根据具体场景自己选择
                mimeMessageHelper.setCc(mailBean.getCcUsers());

            }
            if(!StringUtils.isEmpty(mailBean.getBccUsers())){
                //秘密抄送(发件人,收件人,抄送人都不会看到抄送给谁了)
                mimeMessageHelper.setBcc(mailBean.getBccUsers());
            }
            mimeMessageHelper.setSubject(mailBean.getSubject());
            // 注意<img/>标签,src='cid:jpg','cid'是contentId的缩写,'jpg'是一个标记
            mimeMessageHelper.setText(mailBean.getContent(), true);
            // 加载文件资源,作为附件
            FileSystemResource file = new FileSystemResource(new File(mailBean.getFileUrl()));
            // 调用MimeMessageHelper的addInline方法替代成文件('jpg[标记]', file[文件])
            mimeMessageHelper.addInline(mailBean.getContentId(), file);

            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            logger.error("邮件发送失败", e.getMessage());
        }
    }

    /**
     * 发送基于Freemarker模板的邮件
     * @param mailBean
     * @param map 模板中传入的值
     */
    public void sendTemplateMail(MailBean mailBean,Map<String, Object> map) {
        try {
            MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            //发送者
            mimeMessageHelper.setFrom(mailBean.getSenderUser());
            //接收者
            mimeMessageHelper.setTo(mailBean.getToUsers());
            if(!StringUtils.isEmpty(mailBean.getCcUsers())){
                //抄送人,使用Cc还是Bcc大家根据具体场景自己选择
                mimeMessageHelper.setCc(mailBean.getCcUsers());

            }
            if(!StringUtils.isEmpty(mailBean.getBccUsers())){
                //秘密抄送(发件人,收件人,抄送人都不会看到抄送给谁了)
                mimeMessageHelper.setBcc(mailBean.getBccUsers());
            }
            mimeMessageHelper.setSubject(mailBean.getSubject());
            Template template = configuration.getTemplate(mailBean.getFtlName());
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            mimeMessageHelper.setText(text, true);
            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发送失败", e.getMessage());
        }

    }

}

测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMailApplicationTests {

    @Autowired
    private MailUtil mailUtil;

    /**
     * 发送简单格式的邮件
     * @throws Exception
     */
    @Test
    public void sendSimpleMail() throws Exception {
        MailBean mailBean = new MailBean();
        //发件人
        mailBean.setSenderUser("123@qq.com");
        //收件人
        mailBean.setToUsers(new String[]{"213@qq.com","232@163.com"});
        //抄送人
        mailBean.setCcUsers(new String[]{"412@qq.com"});
        //秘密抄送人
        mailBean.setBccUsers(new String[]{"23235@163.com"});
        //主题
        mailBean.setSubject("测试主题");
        //内容
        mailBean.setContent("测试内容");

        mailUtil.sendSimpleMail(mailBean);

    }

    /**
     * 发送HTML格式的邮件
     * @throws Exception
     */
    @Test
    public void sendHTMLMail() throws Exception {
        MailBean mailBean = new MailBean();
        //发件人
        mailBean.setSenderUser("123@qq.com");
        //收件人
        mailBean.setToUsers(new String[]{"213@qq.com","232@163.com"});
        //抄送人
        mailBean.setCcUsers(new String[]{"412@qq.com"});
        //秘密抄送人
        mailBean.setBccUsers(new String[]{"23235@163.com"});
        //标题
        mailBean.setSubject("测试发送HTML邮件");
        StringBuilder sb = new StringBuilder();
        sb.append("<h1>html格式邮件</h1>")
                .append("<span style='color:red'>测试内容。。。。。。</span> ")
                .append("<hr/>");
        //内容
        mailBean.setContent(sb.toString());

        mailUtil.sendHTMLMail(mailBean);
    }

    /**
     * 发送带附件格式的邮件
     * @throws Exception
     */
    @Test
    public void sendAttachmentMail() throws Exception {
        MailBean mailBean = new MailBean();
        //必须参数:发件人
        mailBean.setSenderUser("123@qq.com");
        //必须参数:收件人
        mailBean.setToUsers(new String[]{"213@qq.com","232@163.com"});
        //可选参数:抄送人
        mailBean.setCcUsers(new String[]{"412@qq.com"});
        //可选参数:秘密抄送人
        mailBean.setBccUsers(new String[]{"23235@163.com"});
        //必须参数:主题
        mailBean.setSubject("测试发送附件");
        //必须参数:内容
        mailBean.setContent("正文部分");
        //必须参数:文件路径
        mailBean.setFileUrl("D:/a.jpg");
        //必须参数:附件名称
        mailBean.setAttachmentFilename("a.jpg");
        
        mailUtil.sendAttachmentMail(mailBean);

    }

    /**
     * 发送带静态资源的邮件
     * @throws Exception
     */
    @Test
    public void sendInlineMail() throws Exception {
        MailBean mailBean = new MailBean();
        //必须参数:发件人
        mailBean.setSenderUser("123@qq.com");
        //必须参数:收件人
        mailBean.setToUsers(new String[]{"213@qq.com","232@163.com"});
        //可选参数:抄送人
        mailBean.setCcUsers(new String[]{"412@qq.com"});
        //可选参数:秘密抄送人
        mailBean.setBccUsers(new String[]{"23235@163.com"});
        //必须参数:主题
        mailBean.setSubject("测试发送带静态资源邮件");
        //必须参数  可以设置为上传文件后缀
        mailBean.setContentId("jpg");
        //必须参数:内容
        mailBean.setContent("\'<html><body>带静态资源的邮件内容:<img src='cid:"+mailBean.getContentId()+"' /></body></html>\'");
        //必须参数:文件路径
        mailBean.setFileUrl("D:/a.jpg");
        mailUtil.sendInlineMail(mailBean);
    }

    /**
     * 发送基于Freemarker模板的邮件
     * @throws Exception
     */
    @Test
    public void sendTemplateMail() throws Exception {
        MailBean mailBean = new MailBean();
        //必须参数:发件人
        mailBean.setSenderUser("123@qq.com");
        //必须参数:收件人
        mailBean.setToUsers(new String[]{"213@qq.com","232@163.com"});
        //可选参数:抄送人
        mailBean.setCcUsers(new String[]{"412@qq.com"});
        //可选参数:秘密抄送人
        mailBean.setBccUsers(new String[]{"23235@163.com"});
        //必须参数:主题
        mailBean.setSubject("测试发送带FreeMarker邮件");
        //必须参数:ftl文件名
        mailBean.setFtlName("mail.ftl");
        Map<String,Object> map =new HashMap<>();
        map.put("content","我是传入ftl模板中的centent属性的值");
        map.put("name","我是传入ftl模板中的name属性的值");
        
        mailUtil.sendTemplateMail(mailBean,map);
    }

}

        注:发送不同格式得邮件得方法都有必须要传入得参数,都有注释。别少传哦! 

src/main/resouce/templates/mail.ftl 模板

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
   name:${name}<br/>
   content:${content}
</body>
</html>

源码地址https://gitee.com/xu0123/springboot2

相关文章