Spring Boot实现发QQ邮件

​

博客主页: 南来_北往

系列专栏:Spring Boot实战


引言

尽管电子邮件已不再是主流的沟通方式,但在职场中仍有不少人偏好使用邮件进行交流。这不仅仅是为了通信,更重要的是作为一种正式的工作记录,确保客户对自己曾经提出的要求和需求负责。

实战

1、第一步添加依赖:

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2、第二进行yml配置:

XML 复制代码
spring:
  mail:
    #smtp服务器
    host: smtp.qq.com
    #发件人
    username: xxx@qq.com
    # 授权码
    password: xxxxx
    #QQ端口号465或587
    port: 587
    default-encoding: UTF-8
    properties:
      timeout: 5000
      connection-timeout: 5000
      write-timeout: 5000
      mail:
        smtp:
          socketFactoryClass: javax.net.ssl.SSLSocketFactory
        #开启调试
        debug: true

3、第三步实现右键接口类:

JavaMailSender javaMailSender

4、第四步进行发送接口:

java 复制代码
void send(MimeMessage mimeMessage)

5、第五进行拼接MimeMessage:

java 复制代码
MimeMessageHelper messageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
//发件人
messageHelper.setFrom(new InternetAddress(name + "<" + form + ">"));
//收件人
messageHelper.setTo(to.split(","));
//主题
messageHelper.setSubject(subject);
//内容
messageHelper.setText(content, isHtml);
//抄送
if (!StringUtils.isEmpty(cc)) {
    messageHelper.setCc(cc.split(","));
}
//密送
if (!StringUtils.isEmpty(bcc)) {
    messageHelper.setCc(bcc.split(","));
}
//附件
if (CollectionUtil.isNotEmpty(files)) {
    for (File file : files) {
        messageHelper.addAttachment(file.getName(), file);
    }
}
// 发送时间
messageHelper.setSentDate(new Date());

6、第六最后messageHelper可以获取MimeMessage:

java 复制代码
messageHelper.getMimeMessage()

邮件设置

首先打开QQ邮箱点击设置:

在账号模块下找到POP3服务来进行打开:

然后需要绑定手机号,按照提示,使用手机给一个账号发短信,然后绑定手机,接着就会得到下面这个授权码:

把这一串授权码填入yml的spring.mail.password。

准备好一切后:

java 复制代码
emailService.sendText("xxx@qq.com",
 "xxxx@qq.com",
 "你好,我是你的朋友",
 "你好,我是你的朋友,我来自加拿大,能和你交个朋友吗?");

可以看到邮件已经发送出去了。

完整代码

java 复制代码
package com.xy.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.xy.service.IEmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.InternetAddress;
import java.io.File;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class EmailServiceImpl implements IEmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    private void send(String form, String to, String subject, String content, Boolean isHtml, String cc, String bcc, List<File> files) {
        
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            //发件人
            messageHelper.setFrom(from);
            //收件人
            messageHelper.setTo(to.split(","));
            //主题
            messageHelper.setSubject(subject);
            //内容
            messageHelper.setText(content, isHtml);
            //抄送
            if (!StringUtils.isEmpty(cc)) {
                messageHelper.setCc(cc.split(","));
            }
            //密送
            if (!StringUtils.isEmpty(bcc)) {
                messageHelper.setCc(bcc.split(","));
            }
            //附件
            if (CollectionUtil.isNotEmpty(files)) {
                for (File file : files) {
                    messageHelper.addAttachment(file.getName(), file);
                }
            }
            // 发送时间
            messageHelper.setSentDate(new Date());
            //正式发送邮件
            javaMailSender.send(messageHelper.getMimeMessage());
        } catch (Exception e) {
            throw new RuntimeException("邮件发送失败", e);
        }
    }


    @Override
    public void sendText(String form, String to, String subject, String content) {
        this.send(form, to, subject, content, false, null, null, null);
    }

    @Override
    public void sendHtml(String form, String to, String subject, String content) {
        this.send( form, to, subject, content, true, null, null, null);
    }

}

关于发件人名称重新取名,可以用下面这个方法:

java 复制代码
messageHelper.setFrom(new InternetAddress("imufather"+ "<" + form + ">"));

但是中文可能会乱码。

相关推荐
椒颜皮皮虾྅9 小时前
让 C# 读懂整张图:DeploySharp 驱动 PaddleOCR v4/v5/v6,打通 OCR 全流程
开发语言·人工智能·深度学习·学习·c#·ocr·cuda
昂好的day9 小时前
C# 同步异步与多线程:Thread / Task / 线程池一次讲透(上篇)
开发语言·windows·c#
Java后端的Ai之路9 小时前
01、Java并发编程:学习攻略如何才能学好并发编程?
java·开发语言·学习
前端 贾公子9 小时前
第 6 章:MCP 服务器介绍与接入
运维·服务器·网络
ScilogyHunter9 小时前
Hercules系列安全MCU功能安全原理详解
java·单片机·安全·hercules
IT_陈寒9 小时前
JavaScript实战技巧总结:深挖数组遍历的性能陷阱与实战解法
前端·人工智能·后端
余槐i9 小时前
PostgreSQL 加索引后查询反而更慢:优化器弃用索引的 3 种情形
spring boot·redis·mysql·postgresql·事务
博风9 小时前
eclipse中配置maven,以及在本地使用maven。
java·eclipse·maven
云-缩影9 小时前
实际项目中怎么选排序算法:从面试题到工程落地
java·算法·排序算法
追星星の人9 小时前
java web项目(eclipse软件)全流程备份
java·servlet