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

但是中文可能会乱码。

相关推荐
字节渡客4 小时前
Redis键明明过期了,业务还在读到旧数据
数据库·redis·spring
daidaidaiyu5 小时前
ThingsBoard 集群的核心逻辑源码分析
java
To_OC5 小时前
从一头雾水到跑通全流程:我用一个周末啃透了JWT登录鉴权
前端·后端·http
2601_962885725 小时前
如何用 Python 自动识别股票的支撑位与压力位?
开发语言·python
爱吃奥利奥_wen5 小时前
面向对象三板斧:封装、继承、多态,到底在“装“什么、“承“什么、“变“什么?
开发语言·经验分享·c#
我可能是个假开发5 小时前
FTP Unicode 文件名导致 `550` 的问题分析与解决方案
java·开发语言·spring
caoerzhong6 小时前
中小企业上 WMS 该先上哪几块:JeeWMS 开源 Java 仓库管理系统的分批上线清单
java·python·开源
前端兰博6 小时前
05-Redis
redis·后端
正在走向自律6 小时前
AI数据分析与可视化:从基础到应用实践
服务器·人工智能·python·机器学习·数据分析·pandas
OnlineProxy6 小时前
亚马逊多账号运营:如何在规避“关联封号”风险的同时实现电商规模化扩张
服务器·数据库·redis