使用java类,实现发邮件的功能

	公司项目,要是实现发邮件的功能,这是功能是很早之前写的,属于榨菜了!
首先在配置文件添加配置
# Spring配置
spring:
  mail:
    host: smtp.163.com
    protocol: smtps
    port: 465
    username: xxxx@163.com #邮箱地址
    password: 12345678 #授权码
    properties: # 配置以SSL的方式发送, 这个需要使用这种方式并且端口是465
      mail:
        smtp:
          auth: true
          ssl:
            enable: true
            socketFactory:
              class: com.sun.mail.util.MailSSLSocketFactory
              fallback: false
        debug: true

配置里需要注意点
prot端口号,我使用的465,一个这个端口号,是需要使用ssl加密的,而且protocol,也要使用smtps,
然后要去163邮箱开通smtp端口,或者qq邮箱,根据各邮箱情况,自己开通获取授权码
代码部分

package com.bosssoft.common.utils;

import com.bosssoft.common.core.domain.vo.FileInfoRespDTO;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeUtility;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;
 
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 邮件发送工具类
 */
@Component
@Slf4j
public class EmailUtil {
    @Resource
    private JavaMailSender mailSender;
 
    @Value("${spring.mail.username}")
    private String from ;// 发件人

    @Value("${email.sender.name}")
    private String senderName ;// 发件人
 
    /**
     * 发送一般邮件--无附件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @return 是否成功
     */
    @SneakyThrows(Exception.class)
    public boolean sendGeneralEmail(String subject, String content, String... to){
        // 创建邮件消息
        org.springframework.mail.SimpleMailMessage message = new org.springframework.mail.SimpleMailMessage();
        message.setFrom(from);
        // 设置收件人
        message.setTo(to);
        // 设置邮件主题
        message.setSubject(subject);
        // 设置邮件内容
        message.setText(content);
        // 发送邮件
        mailSender.send(message);
 
        return true;
    }
    /**
     * 发送带附件的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @param filePaths 附件路径
     * @return 是否成功
     */
    @SneakyThrows(Exception.class)
    public boolean sendAttachmentsEmail(String subject, String content, String[] to, String[] filePaths) {
        // 创建邮件消息
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        // 设置收件人
        helper.setTo(to);
        // 设置邮件主题
        helper.setSubject(subject);
        // 设置邮件内容
        helper.setText(content);
 
        // 添加附件
        if (filePaths != null) {
            for (String filePath : filePaths) {
                FileSystemResource file = new FileSystemResource(new File(filePath));
                helper.addAttachment(Objects.requireNonNull(file.getFilename()), file);
 
            }
        }
        // 发送邮件
        mailSender.send(mimeMessage);
        return true;
    }
 
    /**
     * 发送带静态资源的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @return 是否成功
     */
    @SneakyThrows(Exception.class)
    public boolean sendInlineResourceEmail(String subject, String content, String to) {
        // 创建邮件消息
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        // 设置发件人
        helper.setFrom(from);
        // 设置收件人
        helper.setTo(to);
        // 设置邮件主题
        helper.setSubject(subject);
        //html内容图片
        String contentHtml = "<html><body>"+content+"</body></html>";
        helper.setText(contentHtml, true);

        mailSender.send(mimeMessage);
        return true;
    }

    /**
     * 批量发送带静态资源的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @return 是否成功
     */
    @SneakyThrows(Exception.class)
    public boolean sendInlineResourceEmail(String subject, String content, String[] to) {
        // 创建邮件消息
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        // 设置发件人
        helper.setFrom(from);
        // 设置收件人
        helper.setTo(to);
        // 设置邮件主题
        helper.setSubject(subject);
        //html内容图片
        String contentHtml = "<html><body>"+content+"</body></html>";
        helper.setText(contentHtml, true);

        mailSender.send(mimeMessage);
        return true;
    }

    /**
     * 发送带附件的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @param filePaths 附件路径
     * @return 是否成功
     */
    @SneakyThrows(Exception.class)
    public boolean sendAttachmentsEmail(String subject, String content, String to, String[] filePaths) {
        // 创建邮件消息
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(new InternetAddress(from, senderName));
        // 设置收件人
        helper.setTo(to);
        // 设置邮件主题
        helper.setSubject(subject);
        // 设置邮件内容
        String contentHtml = "<html><body>"+content+"</body></html>";
        helper.setText(contentHtml, true);
        // 添加附件
        if (filePaths != null) {
            for (String filePath : filePaths) {
                FileSystemResource file = new FileSystemResource(new File(filePath));
                helper.addAttachment(Objects.requireNonNull(file.getFilename()), file);
            }
        }
        try {
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            // 如果邮件地址不合法或发送过程中出现异常,则标记为发送失败
            return false;
        }
        return true;
    }

    /**
     * 批量发送带有附件的HTML格式电子邮件。
     *
     * @param subject   邮件主题
     * @param content   邮件正文内容
     * @param emailMap        收件人邮箱列表
     * @param filePaths 附件文件路径数组
     * @return 发送结果的Map,键为邮箱地址,值为发送状态
     */
    public Map<String, Boolean> sendAttachmentsEmailBatch(String subject, Map<String,String> emailMap, String[] filePaths,Map<String, String> files) throws Exception {
        Map<String, Boolean> result = new HashMap<>();
        // 创建邮件消息
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // 加载附件到邮件中
        MimeMessageHelper messageHelper = prepareMessageWithAttachments(mimeMessage, filePaths,files);

        messageHelper.setFrom(new InternetAddress(from, senderName));
        messageHelper.setSubject(subject);

        // 尝试发送邮件给每个收件人
        emailMap.keySet().forEach(email -> {
            try {
                String contentHtml = "<html><body>" + emailMap.get(email) + "</body></html>";
                messageHelper.setText(contentHtml, true);
                messageHelper.setTo(email);
                mailSender.send(mimeMessage);
                log.info("邮件发送成功:" + email);
            } catch (Exception e) {
                // 如果邮件地址不合法或发送过程中出现异常,则标记为发送失败
                result.put(email, false);
            }
        });
        return result;
    }

    /**
     * 预加载附件到邮件中
     * @param mimeMessage
     * @param filePaths
     * @return
     * @throws MessagingException
     */
    private MimeMessageHelper prepareMessageWithAttachments(MimeMessage mimeMessage, String[] filePaths,Map<String, String> files) throws MessagingException, UnsupportedEncodingException {
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        if (filePaths != null) {
            for (String filePath : filePaths) {
                FileSystemResource file = new FileSystemResource(new File(filePath));
                String encodedFileName = MimeUtility.encodeText(file.getFilename(), StandardCharsets.UTF_8.name(), "B");
                helper.addAttachment(Objects.requireNonNull(encodedFileName), file);
            }
        }else{
            Set<String> strings = files.keySet();
            strings.forEach(key->{
                FileSystemResource file = new FileSystemResource(new File(key));
                try {
                    // 对文件名进行编码
                    String fileName = files.get(key);
                    String encodedFileName = MimeUtility.encodeText(fileName, StandardCharsets.UTF_8.name(), "B");
                    helper.addAttachment(Objects.requireNonNull(files.get(key)), file);
                } catch (MessagingException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            });
        }
        return helper;
    }
}

prepareMessageWithAttachments方法设置了两个参数String[] filePaths,Map<String, String> files

filePaths参数是文件路径的数组,
files参数是键是路径,值是文件名的MAP
看清况使用

另外
MimeUtility.encodeText(fileName, StandardCharsets.UTF_8.name(), “B”);是对文件名,进项编码,防止文件中文乱码出现,不过我在使用163邮箱发送的时候,并没有出现这个情况,不知道别的邮箱,会不会出现,备用吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值