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

但是中文可能会乱码。

相关推荐
海兰2 分钟前
【springboot】gradle快速镜像配置
spring boot·笔记·后端
程序员老邢3 分钟前
【技术底稿 10】16G Ubuntu 服务器手动部署 Ollama 0.20.4 全流程(避坑 HTTP2 错误)
服务器·ubuntu·ai·语言模型·devops
cheems95274 分钟前
[SpringMVC] Spring MVC 留言板开发实战
java·spring·mvc
饼瑶4 分钟前
Isaac Sim 5.0.0 Docker 部署手册(实验室服务器)
服务器·docker·容器
dddddppppp1234 分钟前
linux head.s 从第一条指令到start_kernel
linux·运维·服务器
BioRunYiXue5 分钟前
AlphaGenome:DeepMind 新作,基因组学迎来 Alpha 时刻
java·linux·运维·网络·数据库·人工智能·eclipse
武超杰7 分钟前
SpringBoot 整合 Spring Security 实现权限控制
spring boot·后端·spring
Huanzhi_Lin8 分钟前
Nginx本地资源服务器-常用脚本
服务器·前端·nginx·batch·静态资源服务器
fengci.8 分钟前
php反序列化(复习)(第四章)
android·开发语言·学习·php·android studio
Jasmine_llq8 分钟前
《B3923 [GESP202312 二级] 小杨做题》
开发语言·状态标记算法·顺序输入输出算法·递推迭代算法·循环遍历算法·条件终止算法·累加求和算法