springboot整合邮箱功能(实战)

为什么要整合邮箱的服务

邮件发送其实是一个非常常见的需求,用户注册,找回密码、校验码等地方。如果使用短信还需缴费。

这里发送者邮箱选用了163邮箱
在这里插入图片描述

1、pom.xml文件的引用

<!-- springboot 邮件mail -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>2.7.2</version>
        </dependency>

2、yml配置文件中的配置

#邮箱配置
spring:
  mail:
    default-encoding: UTF-8 #默认的邮件编码
    host: smtp.163.com #配置 SMTP 服务器地址
    username: z******1@163.com #配置邮箱用户名
    password: G*********S  #配置密码,注意,不是真正的密码,而是刚刚申请到的授权码
    port: 465 #SMTP 服务器的端口
    properties:
      mail:
        debug: true #表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
        #官方建议使用 465 端口,而 465 端口是 SSL 协议的,所以不仅要换端口,
        #还需要进行 SSL 协议替换。下面是在 application.properties 进行的邮件发送相关配置,
        smtp:
          socketFactory:
            port: 465
          #socketFactoryClass: javax.net.ssl.SSLSocketFactory #配饰 SSL 加密工厂
          ssl:
            enable: true
    protocol: smtp

3、引用配置的参数

@Component("DeployParameter")
public class DeployParameter {
    /**
     * 发送者邮箱
     */
    public static String MAIL_USERNAME;
    @Value("${spring.mail.username}")
    public void setMailUsername(String mailUsername) {
        MAIL_USERNAME = mailUsername;
    }
    /**
     * 文件上传地址
     */
    public static String UPLOAD_URL;
    @Value("${file.upload.url}")
    public void setUploadUrl(String uploadUrl) {
        UPLOAD_URL = uploadUrl;
    }
}

4、创建发送邮箱的实体

/**
 * @Author: zjh
 * @Date: 2022/9/9 16:01
 * @Description: 邮箱字段
 * @Version: v1.0
 */
@Data
public class SendMailModel implements Serializable {

    /**
     *
     */
    @ApiModelProperty(value = "邮件主题")
    private String subject;


    /**
     * 账号
     */
    @ApiModelProperty(value = "收件人邮箱")
    private String[] recipientMailbox;

    /**
     * 账号
     */
    @ApiModelProperty(value = "抄送人邮箱")
    private String[] ccMailbox;

    /**
     * 账号
     */
    @ApiModelProperty(value = "加密抄送人邮箱")
    private String[] bccMailbox;
    /**
     * 密码
     */
    @ApiModelProperty(value = "发送内容")
    private String sendContent;


    /**
     *
     */
    @ApiModelProperty(value = "真实名称/附件路径")
    private Map<String,String> enclosures;

//    @ApiModelProperty(value = "附件是否添加的到正文,默认false不添加")
//    private Boolean is_;


}

5、创建发送邮箱的方法

/**
 * @Author: zjh
 * @Date: 2022/9/9 15:23
 * @Description: 发送邮件功能
 * @Version: v1.0
 */
@Component
public class SendMailUtil {

    @Autowired
    JavaMailSender javaMailSender;

    public void sendMail( SendMailModel model) throws MessagingException {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        helper.setSubject(model.getSubject()); //邮件标题
        helper.setFrom(DeployParameter.MAIL_USERNAME); //发送者邮箱
        helper.setTo(model.getRecipientMailbox()); //收件人邮箱
        if(model.getCcMailbox()!=null && model.getCcMailbox().length!=0){
            helper.setCc(model.getCcMailbox()); //抄送人
        }
        if(model.getBccMailbox()!=null && model.getBccMailbox().length!=0){
            helper.setBcc(model.getBccMailbox()); //加密抄送
        }
        helper.setSentDate(new Date()); //发送日期
        helper.setText(model.getSendContent()); //发送内容
        if(!model.getEnclosures().isEmpty()){
            //通过keySet取出map数据[Iterator遍历]
            System.out.println("-------[Iterator循环遍历]通过keySet取出map数据---------");
            Iterator<String> it = model.getEnclosures().keySet().iterator();  //map.keySet()得到的是set集合,可以使用迭代器遍历
            while(it.hasNext()){
                String key = it.next();
                helper.addAttachment(key, new File(model.getEnclosures().get(key)));//预览文件
                //System.out.println("key值:"+key+" value值:"+model.getEnclosures().get(key));
            }

        }
        //helper.addAttachment("2.jpg", new File("E:\\pic\\2.jpg"));//预览文件
//        helper.addInline("p01",new FileSystemResource(new File("E:\\pic\\2.jpg")));//配合前端可以直接预览图片
//        helper.addInline("p02",new FileSystemResource(new File("E:\\pic\\2.jpg")));
        javaMailSender.send(mimeMessage);
    }



}

注意:收件人,抄送人,加密抄送人,都可以多个。附件的发送附件的位置需要和项目在同一台服务器上。

6、调用该方法

    @PostMapping("/sendMail")
    public ResultJson sendMail(@RequestBody SendMailModel model) throws MessagingException {
        sendMailUtil.sendMail(model);
        return ResultJson.SUCCESS();
    }

7、使用postMan测试该方法请求的参数

{
    "subject":"测试主题",
    "recipientMailbox":["1**********8@qq.com","1*******15@qq.com"],
    "ccMailbox":[],
    "bccMailbox":[],
    "sendContent":"测试邮件测试人**华",
    "enclosures":{
        "20.jpg":"E:/pic/test\\20220915\\vnsjyb9gb2.jpg",
        "timg.jpg":"E:/pic/test\\20220915\\ph5d37sozz.jpg"
    }
}

邮件发送的讲解,作者本身参考该文章写的,如有侵权望告知删除。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值