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 + ">"));

但是中文可能会乱码。

相关推荐
Ronin3053 分钟前
交换机路由管理模块
服务器·rabbitmq·动态规划·交换路由
大尚来也8 分钟前
解决 IDEA 运行 Spring Boot 测试时“命令行过长”错误的终极方案
java·spring boot·intellij-idea
三点水-here9 分钟前
03 - KV Cache与批处理:大模型推理的内存管理核心技术
服务器·人工智能·ai编程
froginwe1110 分钟前
装饰器模式
开发语言
云姜.12 分钟前
如何在idea上使用数据库
java·数据库·intellij-idea
yttandb13 分钟前
linux的基础命令
linux·运维·服务器
未来之窗软件服务15 分钟前
服务器运维(三十五)数字证书TLS 版本设备对照表—东方仙盟
运维·服务器·服务器运维·仙盟创梦ide·东方仙盟
枫叶丹417 分钟前
【Qt开发】Qt界面优化(三)-> Qt样式表(QSS) 设置方式
c语言·开发语言·c++·qt·系统架构
-小麦子-21 分钟前
Python 变量组包、解包及星号扩展机制详解
开发语言·python
lqj_本人23 分钟前
Flutter三方库适配OpenHarmony【apple_product_name】设备型号标识符转换原理
运维·服务器·flutter