SpringBoot邮件发送

参考文章:https://blog.csdn.net/m0_56287495/article/details/136587403

  1. 导入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
  1. 修改yml
spring:
  mail:
    # 配置SMTP服务器地址
    host: smtp.qq.com
    # 发送者邮箱
    username: 123@qq.com
    # 授权码
    password: 123
    # 端口号465或587
    port: 587
    # 默认的邮件编码为UTF-8
    default-encoding: UTF-8
    # 配置SSL 加密工厂
    properties:
      # 设置邮件超时时间防止服务器阻塞
      timeout: 5000
      connection-timeout: 5000
      write-timeout: 5000
      mail:
        smtp:
          socketFactoryClass: javax.net.ssl.SSLSocketFactory
        # 表示开启DEBUG模式,这样邮件发送过程的日志会在控制台打印,方便排除问题
        debug: true
  1. 邮件发送
package com.tjx.email.server;

import java.io.File;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author tianjiaxin
 * @createTime 2024/6/1 16:09
 * @Description:
 */
public interface IEmailService {
    /**
     * 普通邮件发送
     *
     * @param to 发送对象
     * @param subject 主题
     * @param context 内容
     */
    void sendText(String to, String subject, String context);

    /**
     * html邮件发送
     *
     * @param to
     * @param subject
     * @param context
     */
    void sendHtml(String to, String subject, String context);

    /**
     * 邮件发送
     *
     * @param name 发送人名称
     * @param to 发送对象
     * @param subject 主题
     * @param content 内容
     * @param isHtml 是否为html
     * @param cc 抄送,多人用逗号隔开
     * @param bcc 密送,多人用逗号隔开
     * @param files 文件
     */
    void send(String name, String to, String subject, String content, Boolean isHtml, String cc, String bcc, List<File> files);

}
package com.tjx.email.server.impl;

import cn.hutool.core.util.StrUtil;
import com.tjx.email.server.IEmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

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

/**
 * <p>
 *
 * </p>
 *
 * @author tianjiaxin
 * @createTime 2024/6/1 16:14
 * @Description:
 */
@Slf4j
@Service
public class EmailServiceImpl implements IEmailService {


    @Value("${spring.mail.username:123@qq.com}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void sendText(String to, String subject, String context) {
        this.send("TEXT提醒", to, subject, context, false, null, null, null);
    }

    @Override
    public void sendHtml(String to, String subject, String context) {
        this.send("HTML提醒", to, subject, context, true, null, null, null);
    }

    @Override
    public void send(String name, String to, String subject, String content, Boolean isHtml, String cc, String bcc, List<File> files) {
        Assert.isTrue(StrUtil.isNotBlank(from) && StrUtil.isNotBlank(to) && StrUtil.isNotBlank(subject) && StrUtil.isNotBlank(content),
                "发送人,接收人,主题,内容均不可为空!");

        try {
            // 用true作为第二个参数,表示创建的MimeMessageHelper对象将支持多部分内容,即可以添加附件或嵌入图片等
            MimeMessageHelper messageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            // 发件人 eg:小明<2390696908@qq.com>
            messageHelper.setFrom(new InternetAddress(name + "<" + from + ">"));
            messageHelper.setTo(to.split(","));
            messageHelper.setSubject(subject);
            messageHelper.setText(content, isHtml);
            if (!StrUtil.isBlank(cc)) {
                messageHelper.setCc(cc.split(","));
            }
            if (!StrUtil.isBlank(bcc)) {
                messageHelper.setBcc(bcc.split(","));
            }
            if (!CollectionUtils.isEmpty(files)) {
                for (File file : files) {
                    messageHelper.addAttachment(file.getName(), file);
                }
            }
            // 邮件发送时间
//            messageHelper.setSentDate(new Date());
            Calendar calendar = Calendar.getInstance();
            Date time = calendar.getTime();
            calendar.add(Calendar.MINUTE, 5);
            Date newTime = calendar.getTime();
            System.out.println("当前时间:" + time);
            System.out.println("推迟5分钟:" + newTime);
            // 注意:不是真的是延迟推送,而是直接发送,这只是邮件上显示的发送时间
            messageHelper.setSentDate(newTime);

            javaMailSender.send(messageHelper.getMimeMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
  1. 测试代码
@Test
public void sendTest() {
    emailService.sendText("123@163.com", "测试主题", "测试内容");
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值