Springboot中配置Mail和普通mail的实现方式

 更新时间:2024年03月05日 10:10:54   作者:喵喵@香菜  
这篇文章主要介绍了Springboot中配置Mail和普通mail的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

一、开通SMTP

SMTP是一种简单的邮件传输协议,SMTP只能够推送邮件,如果想要在邮件服务器上下拉邮件,可以使用POP3或者IMAP协议。

自己的邮箱就可以开通SMTP,以QQ邮箱为例(163或者其他邮箱开通大同小异)

1)打开自己的QQ邮箱—【设置】—【账户】—【POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务】

将这几个开启,如果你没有开启的话,开启后点击页面上的【生成授权码】,然后根据提示(发送短信)操作就可以。

这里的授权码在代码中要用到,用于发送邮件时的密码,注意这里不是登陆邮箱的密码,可以生成多个授权码,有这个授权码就可以通过你的邮箱发送邮件。

开通完毕

二、springboot中配置mail(spring boot环境已经搭好)

1)application.yml文件如下

spring:
  mail:
    #如果是163  就为  smtp.163.com
    host: smtp.qq.com
    #刚才开通了SMTP的QQ邮箱
    username: 你的QQ邮箱@foxmail.com
    # 在页面生成的授权码
    password: 授权码
    default-encoding: utf-8
    protocol: smtp
    # 默认端口
    port: 25
    properties:
      mail:
        smtp:
          # 设置是否需要认证,如果为true,那么用户名和密码就必须的,
          # 如果设置false,可以不设置用户名和密码,当然也得看你的对接的平台是否支持无密码进行访问的。
          auth: true
          starttls:
            # STARTTLS[1]  是对纯文本通信协议的扩展。它提供一种方式将纯文本连接升级为加密连接(TLS或SSL),而不是另外使用一个端口作加密通信。
            enable: true
            required: true

#邮件配置(自定义设置,主要配置了收件人和发件人,这些可以当做发送邮件的参数)  
mail-config:
  environmental: 邮件测试 
  # 发件人邮箱
  from: 发件人@foxmail.com
  # 收件人邮箱(抄送人)
  recipient:
    - "收件人1的邮箱@foxmail.com"
    - "收件人2的邮箱@qq.com" 

2)maven依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

3)读取发件人和收件人配置类

package com.zlc.mail.coonfig;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * @描述 : 邮件配置
 * @Author :  追到乌云的尽头找太阳
 * @Date : 2019/10/18 14:52
 **/
@Configuration
@ConfigurationProperties(prefix = "mail-config")
public class MailConfig {
    
    private String environmental;
    private String from;
    private String [] recipient = null;

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String[] getRecipient() {
        return recipient;
    }

    public void setRecipient(String[] recipient) {
        this.recipient = recipient;
    }

    public String getEnvironmental() {
        return environmental;
    }

    public void setEnvironmental(String environmental) {
        this.environmental = environmental;
    }
}

4)发送邮件工具类

package com.zlc.mail.util;

import com.zlc.mail.coonfig.MailConfig;
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.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @描述 : 邮件工具
 * @Author :  zlc
 * @Date : 2019/10/10 16:41
 **/
@Component
public class MailUtil {
    
    private final JavaMailSender mailSender;
    private final MailConfig mailConfig;
    
    public MailUtil(JavaMailSender mailSender , MailConfig mailConfig) {
        this.mailSender = mailSender;
        this.mailConfig = mailConfig;
    }

    public void sendSimpleMail(String subject, String content) {
        // new 一个简单邮件消息对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 和配置文件中的的username相同,相当于发送方
        message.setFrom(mailConfig.getFrom());
        // setCc 抄送,setTo 发送,setBCc密送
        message.setCc(mailConfig.getRecipient());
        message.setSubject("【类型】:【文本】-【来源】【" + mailConfig.getEnvironmental() + "】-主题【" + subject + "】");
        // 正文
        message.setText(content);
        // 发送
        mailSender.send(message);
    }

    public void sendHtmlMail(String subject, String content) {

        //使用MimeMessage,MIME协议
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper;
        //MimeMessageHelper帮助我们设置更丰富的内容
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailConfig.getFrom());
            helper.setTo(mailConfig.getRecipient());
            helper.setSubject("【类型】:【HTML】【来源】-【" + mailConfig.getEnvironmental() + "】-主题【" + subject + "】");
            //true代表支持html
            helper.setText(content, true);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
           // logger.error("发送HTML邮件失败:", e);
        }
    }

    public void sendAttachmentMail(String subject, String content, File file) {

        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            //true代表支持多组件,如附件,图片等
            helper.setFrom(mailConfig.getFrom());
            helper.setTo(mailConfig.getRecipient());
            helper.setSubject("【类型】:【附件】-【来源】-【" + mailConfig.getEnvironmental() + "】-主题【" + subject + "】");
            helper.setText(content, true);
            FileSystemResource file1 = new FileSystemResource(file);
            String fileName = file1.getFilename();
            //添加附件,可多次调用该方法添加多个附件  
            helper.addAttachment(fileName, file1);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public void sendInlineResourceMail(String subject, String content, String rscPath, String rscId) {

        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailConfig.getFrom());
            helper.setTo(mailConfig.getRecipient());
            helper.setSubject("【类型】:【图片】-【来源】-【" + mailConfig.getEnvironmental() + "】-主题【" + subject + "】");
            helper.setText(content, true);
            FileSystemResource res = new FileSystemResource(new File(rscPath));
            //重复使用添加多个图片
            helper.addInline(rscId, res);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }


}

三、普通发送邮件的类,和是否SpringBoot没关系

package com.zlc.mail.javamail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * @author : 追到乌云的尽头找太阳-(Jacob)
 * @date : 2019/10/29 17:51
 **/
public class MailUtil {
    
    public static void sendImageMail(String subject, String conent, String imagePath ) throws MessagingException {
        // 邮件配置文件
        Properties properties = new Properties();
        properties.setProperty("mail.protocol","smtp");
        properties.setProperty("mail.host","smtp.qq.com");
        properties.setProperty("mail.smtp.auth", "true");
        //发送邮件时使用的环境配置
        Session session = Session.getInstance(properties);
        //session.setDebug(true);
        
        MimeMessage message = new MimeMessage(session);

        //设置邮件的头
        message.setFrom(new InternetAddress("发件人邮箱地址@foxmail.com"));
        message.setRecipients(Message.RecipientType.TO, "收件人邮箱@foxmail.com");
        message.setSubject("【人脸识别】-【主题】-【" + subject + "】");

        //设置正文

        //搞出文本部分
        MimeBodyPart textPart = new MimeBodyPart();
       

        //搞图片部分
        MimeBodyPart imagePart = new MimeBodyPart();
        imagePart.setContentID("mm");
        //把磁盘上的文件加到part中使用到了JAF框架
        try {
            DataHandler dh = new DataHandler(new FileDataSource(imagePath));
            imagePart.setDataHandler(dh);
        }catch (Exception e){
            e.printStackTrace();
            conent+="读取图片异常,异常信息为:" + e.getMessage();
        }
        textPart.setContent("<h3>内容:"+ conent +"<br/><img src='cid:mm'/>", "text/html");
        

        MimeMultipart mp = new MimeMultipart();
        mp.addBodyPart(textPart);
        mp.addBodyPart(imagePart);
        //有关系的
        mp.setSubType("related");

        message.setContent(mp);
        message.saveChanges();

        //发送邮件
        Transport ts = session.getTransport();
        //密码为授权码不是邮箱的登录密码
        ts.connect("开通了smtp的邮箱地址@foxmail.com", "授权码");
        //对象,用实例方法
        ts.sendMessage(message, message.getAllRecipients());
    }
    
    public static void sendEnclosureMail(String subject, String conent ,String imagePath, String filePath) throws MessagingException {

        Properties props = new Properties();
        props.setProperty("mail.protocol", "smtp");
        props.setProperty("mail.host", "smtp.qq.com");
        props.setProperty("mail.smtp.auth", "true");
        Session session = Session.getInstance(props);
        //发送邮件时使用的环境配置
        MimeMessage message = new MimeMessage(session);

        //设置邮件的头
        message.setFrom(new InternetAddress("发件人邮箱地址@foxmail.com"));
        message.setRecipients(Message.RecipientType.TO, "收件人邮箱地址@foxmail.com");
        message.setSubject("【人脸识别】-【主题】-【" + subject + "】");
        //设置正文
        //搞出文本部分
        MimeBodyPart textPart = new MimeBodyPart();
        MimeBodyPart imagePart = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource(""));
        
        if ("" != imagePath || null != imagePath) {
            textPart.setContent("图片<img src='cid:mm'/>", "text/html;charset=UTF-8");
            //搞图片部分
            imagePart.setContentID("mm");
            //把磁盘上的文件加到part中使用到了JAF框架
            dh = new DataHandler(new FileDataSource(imagePath));
            imagePart.setDataHandler(dh);
        }

        MimeMultipart mp = new MimeMultipart();
        mp.addBodyPart(textPart);
        mp.addBodyPart(imagePart);
        mp.setSubType("related");

        MimeBodyPart textImagePart = new MimeBodyPart();    
        textImagePart.setContent(mp);

        //创建附件部分
        MimeBodyPart attachmentPart = new MimeBodyPart();
        if ("" != filePath || null != filePath){
            dh = new DataHandler(new FileDataSource(filePath));
        }
       
        String filename = dh.getName();
        attachmentPart.setDataHandler(dh);

        //手工设置文件名  防止乱码使用  javaMail里的 MimeUtility进行编码
        try {
            attachmentPart.setFileName(MimeUtility.encodeText(filename));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //最终的 MimeMultipart
        MimeMultipart finalMp = new MimeMultipart();
        finalMp.addBodyPart(attachmentPart);
        finalMp.addBodyPart(textImagePart);

        finalMp.setSubType("mixed");

        message.setContent(finalMp);
        message.saveChanges();

        //发送邮件
        Transport ts = session.getTransport();
        ts.connect("开启了smtp的邮箱地址@foxmail.com", "授权码");
        ts.sendMessage(message, message.getAllRecipients());
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java Maven Settings配置参考教程

    Java Maven Settings配置参考教程

    这篇文章主要介绍了Java Maven Settings配置参考,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-09-09
  • Spring中allowedOriginPatterns和allowedOrigins方法有何不同详解

    Spring中allowedOriginPatterns和allowedOrigins方法有何不同详解

    这篇文章主要给大家介绍了关于Spring中allowedOriginPatterns和allowedOrigins方法有何不同,allowedOriginPatterns和allowedOrigins都是用来设置允许跨域请求的来源,需要的朋友可以参考下
    2023-10-10
  • SpringBoot项目中的多数据源支持的方法

    SpringBoot项目中的多数据源支持的方法

    本篇文章主要介绍了SpringBoot项目中的多数据源支持的方法,主要介绍在SpringBoot项目中利用SpringDataJpa技术如何支持多个数据库的数据源,有兴趣的可以了解一下
    2017-10-10
  • SpringBoot validator参数验证restful自定义错误码响应方式

    SpringBoot validator参数验证restful自定义错误码响应方式

    这篇文章主要介绍了SpringBoot validator参数验证restful自定义错误码响应方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • 详解Maven环境的搭建与idea配置

    详解Maven环境的搭建与idea配置

    本篇文章主要介绍了详解Maven环境的搭建与idea配置,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • JavaWeb组件Servlet使用实例解析

    JavaWeb组件Servlet使用实例解析

    这篇文章主要介绍了JavaWeb组件Servlet使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • java中单例模式讲解

    java中单例模式讲解

    这篇文章主要介绍了java中单例模式,本文通过简单的案例,讲解了该模式在java中的使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • Spring Boot 3.4.0 结合 Mybatis-plus 实现动态数据源的完整方案

    Spring Boot 3.4.0 结合 Mybatis-plus 实

    本文详细介绍了在 Spring Boot 3.4.0 项目中结合 Mybatis-plus 实现动态数据源切换的完整方案,通过自定义注解和AOP切面,我们可以优雅地实现方法级别的数据源切换,满足多数据源场景下的各种需求,感兴趣的朋友一起看看吧
    2025-04-04
  • Java设计模式之Iterator模式介绍

    Java设计模式之Iterator模式介绍

    所谓Iterator模式,即是Iterator为不同的容器提供一个统一的访问方式。本文以java中的容器为例,模拟Iterator的原理。需要的朋友可以参考下
    2013-07-07
  • Java日期处理工具类DateUtils详解

    Java日期处理工具类DateUtils详解

    这篇文章主要为大家详细介绍了Java日期处理工具类DateUtils的相关代码,包含日期和时间常用操作,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-12-12

最新评论