mitao
2025-03-19 0ab9dfd8f122195e4e9f09bd50c59e0a47450bec
ruoyi-common/src/main/java/com/ruoyi/common/utils/TencentMailUtil.java
New file
@@ -0,0 +1,203 @@
package com.ruoyi.common.utils;
import com.ruoyi.common.config.MailProperties;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import java.net.URLEncoder;
import javax.activation.URLDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
@Component
@Slf4j
public class TencentMailUtil {
    @Autowired
    MailProperties properties;
    public MailProperties getPro() {
        return properties;
    }
    /**
     *
     * @param emailAddress  邮件接收者email地址
     * @param param 用户房屋地址参数
     */
    public void send(String emailAddress,String param){
        // 配置发送邮件的环境属性
        final Properties props = new Properties();
        // 表示SMTP发送邮件,需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", properties.getSmtpHost());
        // 如果使用ssl,则去掉使用25端口的配置,进行如下配置,
        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());
        // 发件人的账号,填写控制台配置的发信地址,比如xxx@xxx.com
        props.put("mail.user", properties.getUserAddr());
        // 访问SMTP服务时需要提供的密码(在控制台选择发信地址进行设置)
        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");
        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息,创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
//        mailSession.setDebug(true);
        //UUID uuid = UUID.randomUUID();
        //final String messageIDValue = "<" + uuid.toString() + ">";
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession) {
            //@Override
            //protected void updateMessageID() throws MessagingException {
            //设置自定义Message-ID值
            //setHeader("Message-ID", messageIDValue);
            //}
        };
        try {
            // 设置发件人邮件地址和名称。填写控制台配置的发信地址,比如xxx@xxx.com。和上面的mail.user保持一致。名称用户可以自定义填写。
            InternetAddress from = new InternetAddress(properties.getUserAddr(), properties.getUserName());
            message.setFrom(from);
            //可选。设置回信地址
//            Address[] a = new Address[1];
//            a[0] = new InternetAddress("***");
//            message.setReplyTo(a);
            // 设置收件人邮件地址,比如yyy@yyy.com
            InternetAddress to = new InternetAddress(emailAddress);
            message.setRecipient(MimeMessage.RecipientType.TO, to);
            //如果同时发给多人,才将上面两行替换为如下(因为部分收信系统的一些限制,尽量每次投递给一个人;同时我们限制单次允许发送的人数是50人):
            // 设置邮件标题
            message.setSubject("您的"+param+"账单提醒");
            message.setHeader("Content-Transfer-Encoding", "base64");
            // 设置邮件的内容体 type: text/plain(纯文本)text/html(HTML 文档)
            message.setContent("邻居您好!您"+param+",提醒您有账单需要处理,如已处理请忽略此短信,感谢您的支持!如有疑问请详询:4008888888。", "text/html;charset=UTF-8");
            //发送邮件
            Transport.send(message);
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("发送邮件发生异常",e);
            throw new ServiceException("发送邮件失败,请检查");
        }catch (Exception e){
            e.printStackTrace();
            log.error("发送邮件发生异常",e);
        }
    }
    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 = createMultipart(list);
            // 设置邮件内容
            message.setContent(multipart);
            // 发送邮件
            Transport.send(message);
        } catch (MessagingException | UnsupportedEncodingException | MalformedURLException e) {
            log.error("发送邮件发生异常", e);
            throw new ServiceException("发送邮件失败, 请检查");
        }
    }
    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);
            }
        };
    }
    private Multipart createMultipart(List<Map<String, String>> list) throws MessagingException, UnsupportedEncodingException, MalformedURLException {
        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);
        // 添加附件部分
        for (Map<String, String> map : list) {
            messageBodyPart = new MimeBodyPart();
            String url = map.get("url");
            String fileName = map.get("fileName");
            URLDataSource source = new URLDataSource(new URL(url));
            messageBodyPart.setDataHandler(new DataHandler(source));
            String filenameEncode = MimeUtility.encodeText(fileName, "UTF-8", "base64");
            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);
        }
        return multipart;
    }
   // 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栋");
   // }
}