SpringBoot整合邮件功能(带附件)

前言

这篇文章只是记录一下在开发中使用邮箱功能

本人在项目中需要使用邮箱发送带附件的邮件,我们的附件可能是在线的阿里云OSS,也可能是系统生成的Excel,写了一个工具类,方便使用。

整合流程

QQ邮箱作为案例
1、添加依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

2、添加配置

spring:
	mail:
	    username: ************@qq.com
	    default-encoding: utf-8
	    host: smtp.qq.com
	    port: 465 #端口号465587
	
	    password: **************#客户端授权码,不是邮箱密码,这个在qq邮箱设置里面自动生成的
	    properties:
	      mail:
	        smtp:
	          auth: true
	          socketFactory:
	            class: javax.net.ssl.SSLSocketFactory
	            fallback: false
	          ssl:
	            enable: true
	            trust: smtp.qq.com

3、工具类

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * 邮箱工具
 */
@Slf4j
@Component
public class MailUtils {
    @Autowired
    private JavaMailSender mailSender;
    /**
     * 配置文件中我的qq邮箱
     */
    @Value("${spring.mail.username}")
    private String username;

    /**
     * 发送邮件-不包含附件
     *
     * @param fromAliasName 别名
     * @param toMail        发送目标邮箱
     * @param subject       主题
     * @param content       内容
     */
    public void sendMail(String fromAliasName, String toMail, String subject, String content) {
        sendMailOssFile(fromAliasName, toMail, subject, content, null);
    }

    /**
     * 发送邮件工具-OSS在线文件
     *
     * @param fromAliasName 别名
     * @param toMail        发送目标邮箱
     * @param subject       主题
     * @param content       内容
     * @param fileList      附件OSS地址
     */
    public void sendMailOssFile(String fromAliasName, String toMail, String subject, String content, List<String> fileList) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            // 设置发件人别名(如果未设置别名就默认为发件人邮箱)
            if (fromAliasName != null && !fromAliasName.trim().isEmpty()) {
                helper.setFrom(new InternetAddress(username, fromAliasName));
            } else {
                helper.setFrom(username);
            }
            helper.setTo(toMail);
            helper.setSubject(subject);
            helper.setText(content, true);
            if (fileList != null && !fileList.isEmpty()) {
                for (String filePath : fileList) {
                    String[] split = filePath.split("/");
                    // 将输入流转换为Resource
                    URL url = new URL(filePath);
                    DataSource dataSource = new URLDataSource(url);
                    helper.addAttachment(split[split.length - 1], dataSource);
                }
            }
            //发送邮件
            mailSender.send(message);
            log.info("邮件已经发送。");
        } catch (MalformedURLException e) {
            log.error("URL 格式错误: {}", e.getMessage(), e);
        } catch (MessagingException | UnsupportedEncodingException e) {
            log.error("发送邮件时发生异常: {}", e.getMessage(), e);
        }
    }


    /**
     * 发送邮件工具-普通文件
     *
     * @param fromAliasName 别名
     * @param toMail        发送目标邮箱
     * @param subject       主题
     * @param content       内容
     * @param fileList      附件
     */
    public void sendMailFile(String fromAliasName, String toMail, String subject, String content, List<File> fileList) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            // 设置发件人别名(如果未设置别名就默认为发件人邮箱)
            if (fromAliasName != null && !fromAliasName.trim().isEmpty()) {
                helper.setFrom(new InternetAddress(username, fromAliasName));
            } else {
                helper.setFrom(username);
            }
            helper.setTo(toMail);
            helper.setSubject(subject);
            helper.setText(content, true);
            if (fileList != null && !fileList.isEmpty()) {
                for (File file : fileList) {
                    helper.addAttachment(file.getName(), new FileSystemResource(file));
                }
            }
            //发送邮件
            mailSender.send(message);
            log.info("邮件已经发送。");
        } catch (MessagingException | UnsupportedEncodingException e) {
            log.error("发送邮件时发生异常!", e);
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值