Spring boot中配置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());
    }
}

Spring Boot 提供了一个方便的 starter 来配置和使用邮件发送功能。要配置 Spring Boot Starter Mail,请按照以下步骤进行操作: 1. 添加依赖:在 Maven 项目的 pom.xml 文件,添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 2. 配置邮件发送参数:在 application.properties 或 application.yml 文件,添加以下配置信息: **application.properties:** ```properties # 邮件服务器主机名 spring.mail.host=your-mail-server-host # 邮件服务器端口号 spring.mail.port=your-mail-server-port # 邮件发送者用户名 spring.mail.username=your-mail-username # 邮件发送者密码 spring.mail.password=your-mail-password # 邮件发送者地址 spring.mail.from=your-mail-from-address # 邮件协议,默认为 smtp spring.mail.protocol=smtp # 邮件发送默认编码,默认为 UTF-8 spring.mail.default-encoding=UTF-8 ``` **application.yml:** ```yaml spring: mail: host: your-mail-server-host port: your-mail-server-port username: your-mail-username password: your-mail-password from: your-mail-from-address protocol: smtp default-encoding: UTF-8 ``` 请将 `your-mail-server-host`、`your-mail-server-port`、`your-mail-username`、`your-mail-password`、`your-mail-from-address` 替换为你的实际邮件服务器和账户信息。 3. 使用 JavaMailSender 发送邮件:在需要发送邮件的地方,注入 `JavaMailSender` 对象,并调用相关方法发送邮件。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service public class EmailService { @Autowired private JavaMailSender javaMailSender; public void sendEmail(String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); javaMailSender.send(message); } } ``` 以上是一个简单的邮件发送示例,你可以根据自己的业务需求进行扩展。记得在需要使用邮件发送的地方注入 `EmailService` 并调用相应的方法即可。 这就是配置和使用 Spring Boot Starter Mail 的基本步骤。希望对你有所帮助!如有更多问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵喵@香菜

感谢观众老爷送的一发火箭!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值