xuhy
2025-03-21 fd6e1e93f65bde3e1c8c15f36b2ff6324d071966
ruoyi-common/src/main/java/com/ruoyi/common/utils/TencentMailUtil.java
@@ -2,17 +2,26 @@
import com.ruoyi.common.config.MailProperties;
import com.ruoyi.common.exception.ServiceException;
import com.sun.xml.internal.org.jvnet.mimepull.MIMEMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
@Component
@Slf4j
@@ -45,7 +54,8 @@
        // 访问SMTP服务时需要提供的密码(在控制台选择发信地址进行设置)
        props.put("mail.password", properties.getPassword());
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.ssl.enable", "false");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");
        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
@@ -89,20 +99,111 @@
            //发送邮件
            Transport.send(message);
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("发送邮件发生异常",e);
            throw new ServiceException("发送邮件失败,请检查");
        }catch (Exception e){
            e.printStackTrace();
            log.error("发送邮件发生异常",e);
        }
    }
//    public static void main(String[] args) {
//        TencentMailUtil tencentMailUtil = new TencentMailUtil();
//        MailProperties properties = new MailProperties();
//        tencentMailUtil.properties = properties;
//        tencentMailUtil.send("214491528@qq.com","大学城揽院24栋");
//
//    }
    public void sendInvoice(String emailAddress, List<Map<String, String>> list) {
        // 异步发送邮件
        CompletableFuture.runAsync(() -> {
            try {
                sendEmail(emailAddress, list);
            } catch (ServiceException e) {
                log.error("邮件发送失败", e);
            }
        });
    }
    private void sendEmail(String emailAddress, List<Map<String, String>> list) throws ServiceException {
        try {
            // 创建邮件会话
            Session mailSession = Session.getInstance(getMailProperties(), getAuthenticator());
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人
            InternetAddress from = new InternetAddress(properties.getUserAddr(), properties.getUserName());
            message.setFrom(from);
            // 设置收件人
            InternetAddress to = new InternetAddress(emailAddress);
            message.setRecipient(MimeMessage.RecipientType.TO, to);
            // 设置邮件标题
            message.setSubject("发票");
            // 创建邮件内容
            Multipart multipart = new MimeMultipart();
            // 添加文本消息部分
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setHeader("Content-Type", "text/plain;charset=utf-8");
            messageBodyPart.setContent("您在小程序提交的开票申请已开票成功,请查看附件内容","text/html;charset=UTF-8");
            multipart.addBodyPart(messageBodyPart);
            List<Path> tempFilePath = new ArrayList<>();
            // 添加附件部分
            for (Map<String, String> map : list) {
                messageBodyPart = new MimeBodyPart();
                String filePath = map.get("filePath");
                String fileName = map.get("fileName");
                tempFilePath.add(Paths.get(filePath));
                FileDataSource source = new FileDataSource(filePath);
                messageBodyPart.setDataHandler(new DataHandler(source));
                String filenameEncode = MimeUtility.encodeText(fileName, "UTF-8", "base64");
                // String encodedFileName = Base64.getEncoder().encodeToString(fileName.getBytes(StandardCharsets.UTF_8));
                // String filenameEncode = MimeUtility.encodeText(encodedFileName);
                messageBodyPart.setFileName(filenameEncode);
                messageBodyPart.setHeader("Content-Transfer-Encoding", "base64");
                messageBodyPart.setHeader("Content-Disposition", "attachment");
                messageBodyPart.setHeader("Content-Type", "application/octet-stream;name=\"" + filenameEncode + "\"");
                multipart.addBodyPart(messageBodyPart);
            }
            // 设置邮件内容
            message.setContent(multipart);
            // 发送邮件
            Transport.send(message);
            // 删除临时目录里面的文件
            for (Path path : tempFilePath) {
                Files.deleteIfExists(path);
            }
        } catch (MessagingException | UnsupportedEncodingException | MalformedURLException e) {
            log.error("发送邮件发生异常", e);
            throw new ServiceException("发送邮件失败, 请检查");
        } catch (IOException e) {
            throw new RuntimeException("文件下载发生异常");
        }
    }
    private Properties getMailProperties() {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", properties.getSmtpHost());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port", properties.getSmtpPort());
        props.put("mail.smtp.port", properties.getSmtpPort());
        props.put("mail.user", properties.getUserAddr());
        props.put("mail.password", properties.getPassword());
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");
        return props;
    }
    private Authenticator getAuthenticator() {
        return new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                String userName = properties.getUserAddr();
                String password = properties.getPassword();
                return new PasswordAuthentication(userName, password);
            }
        };
    }
   // public static void main(String[] args) throws UnsupportedEncodingException {
   //     TencentMailUtil tencentMailUtil = new TencentMailUtil();
   //     MailProperties properties = new MailProperties();
   //     tencentMailUtil.properties = properties;
   //     tencentMailUtil.send("645025773@qq.com","大学城揽院24栋");
   // }
}