Java 发送邮件(2024-03)

1\

2\

package org.jeecg.common.util.io;

import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.*;

@Slf4j
public class MailUtil {
    private static final String sendEmail = "xxxx@qq.com";
    // private static final String receiveEmail = "xxxx@qq.com";
    private static final String host = "smtp.qq.com";
    private static final String password = "xxxxxxxxx";

    public static void main(String[] args) throws Exception {
        String receiveEmail = "xxxx@qq.com";
        String filePath = "C:\\Users\\xxxxx\\Desktop\\微信图片_20240322192242.jpg";
        sendQQEmail(Arrays.asList(receiveEmail), "主题", "自测内容 " + DateUtils.getNowStr());
        sendQQEmailHasFile(Arrays.asList(receiveEmail), "主题", "自测内容 " + DateUtils.getNowStr(), Arrays.asList(new File(filePath)));
    }

    private static Boolean sendQQEmail(List<String> receiveEmails, String subject, String content) throws Exception {
        Session session = getSession(host, sendEmail, password);
        return send(session, sendEmail, receiveEmails, subject, content, null);
    }

    private static Boolean sendQQEmailHasFile(List<String> receiveEmails, String subject, String content, List<File> fileList) throws Exception {
        Session session = getSession(host, sendEmail, password);
        return send(session, sendEmail, receiveEmails, subject, content, fileList);
    }

    private static Boolean send(Session session, String sendEmail, List<String> receiveEmails, String subject, String content, List<File> fileList) throws Exception {
        try {
            MimeMessage message = new MimeMessage(session);
            //防止邮件被当然垃圾邮件处理,披上Outlook的马甲
            message.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
            message.setFrom(new InternetAddress(sendEmail));
            List<InternetAddress> addressList = new ArrayList<>();
            for (String receive : receiveEmails) {
                addressList.add(new InternetAddress(receive));
            }
            InternetAddress[] array = addressList.stream().toArray(InternetAddress[]::new);
            message.addRecipients(Message.RecipientType.TO, array);
            message.setSubject(subject);
            // message.setText(content);

            BodyPart bodyPart_text = new MimeBodyPart();
            bodyPart_text.setText(content);

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(bodyPart_text);

            List<BodyPart> bodyPartList = getBodyPartList(fileList);
            bodyPartList.forEach(a -> {
                try {
                    multipart.addBodyPart(a);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            });

            message.setContent(multipart);

            Transport.send(message);

            String msg = DateUtils.getNowStrForLogPre()
                    + String.format("邮件发送成功,发送者:%s,接收者:%s,主题:%s,内容:%s", sendEmail, receiveEmails, subject, content);
            log.info(msg);

            return true;
        } catch (Exception e) {
            String msg = DateUtils.getNowStrForLogPre()
                    + String.format("邮件发送失败:%s,发送者:%s,接收者:%s,主题:%s,内容:%s", e.getMessage(), sendEmail, receiveEmails, subject, content);
            log.error(msg, e);
            return false;
        }
    }

    private static List<BodyPart> getBodyPartList(List<File> fileList) throws Exception {
        List<BodyPart> partList = new ArrayList<>();
        if (fileList == null || fileList.size() <= 0) {
            return partList;
        }
        for (File file : fileList) {
            BodyPart bodyPart_curr = new MimeBodyPart();
            DataSource dataSource = new FileDataSource(file.getPath());
            bodyPart_curr.setDataHandler(new DataHandler(dataSource));
            bodyPart_curr.setFileName(file.getName());
            partList.add(bodyPart_curr);
        }
        return partList;
    }

    private static Session getSession(String host, String userName, String password) throws Exception {
        Properties properties = System.getProperties();
        MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
        sslSocketFactory.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.auth", "true");
        // properties.put("mail.smtp.starttls.enable", "true");

        return Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        });
    }
}

posted @ 2024-03-27 18:20  一只桔子2233  阅读(63)  评论(0编辑  收藏  举报