java利用网易邮箱批量发送邮件(带附件)

前言

来个需求,需要给注册用户发送特定的邮件内容,所以就有了这篇博文咯。

准备条件(本文以网易邮箱为例)

邮箱账号必须要开启 SMTP 服务

设置授权码

编码实现

maven

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
	<version>1.4.7</version>
</dependency>
EmailUtil

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * @Author 954
 * @create 2019/6/27 13:46
 */
public class EmailUtil {

    // 发送者别名
    private static final String SENDER_NAME = "XXX" ;

    // 发送邮箱地址
    private static final String SENDER_ADDRESS = "[email protected]" ;

    // 发送邮箱的授权码
    private static final String SENDER_PWD = "XXX" ;

    // 密送的邮箱地址
    private static final String PRIVATE_ADDRESS = "[email protected]" ;

    /**
     * 发送邮件的环境对象
     */
    private static final Session EMAIL_SESSION = getEmailSession();

    /**
     * 批量发送电子邮件
     * @param emailAddressList  邮箱地址
     * @param content           邮件内容
     * @param title             邮件标题
     * @param fileList          附件
     * @throws Exception
     */
    public synchronized void sendEmail(List<String> emailAddressList, String title, String content, List<File> fileList) throws Exception {
        MimeMessage mimeMessage = getMimeMessage(emailAddressList, title, content);
        if (!CollectionUtils.isEmpty(fileList)){
            // 处理附件
            Multipart multipart = getMultipart(fileList);
            mimeMessage.setContent(multipart);
            //  添加邮件内容
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(content, "text/html;charset=UTF-8");
            // 将multipart对象放入message中
            multipart.addBodyPart(contentPart);
        }
        Transport.send(mimeMessage);
    }

    private MimeMessage getMimeMessage(List<String> emailAddressList, String title, String content) throws Exception {
        // 创建邮件消息
        MimeMessage message = new MimeMessage(EMAIL_SESSION);
        // 设置发件人
        message.setFrom(new InternetAddress(SENDER_ADDRESS, SENDER_NAME));
        // 设置收件人
        InternetAddress[] address = new InternetAddress[emailAddressList.size()] ;
        for (int i = 0; i < emailAddressList.size(); i++){
            address[i] = new InternetAddress(emailAddressList.get(i)) ;
        }
        message.setRecipients(Message.RecipientType.TO, address);
        // 设置密送
        message.setRecipient(Message.RecipientType.BCC, new InternetAddress(PRIVATE_ADDRESS));
        // 设置邮件标题
        message.setSubject(title, "UTF-8");
        // 设置邮件的内容体
        message.setContent(content, "text/html;charset=UTF-8");
        // 设置发送时间
        message.setSentDate(new Date());
        return message;
    }

    private Multipart getMultipart(List<File> fileList) {
        if (CollectionUtils.isEmpty(fileList)) return null;
        Multipart multipart = new MimeMultipart();
        // 添加附件的内容
        fileList.stream().parallel().forEach(file -> {
            try {
                BodyPart attachmentBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(file);
                attachmentBodyPart.setDataHandler(new DataHandler(source));
                // MimeUtility.encodeWord可以避免文件名乱码
                attachmentBodyPart.setFileName(MimeUtility.encodeWord(file.getName()));
                multipart.addBodyPart(attachmentBodyPart);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return multipart ;
    }

    private static Session getEmailSession(){
        // 配置发送邮件的环境属性
        Properties props = new Properties();
        //设置用户的认证方式
        props.setProperty("mail.smtp.auth", "true");
        //设置传输协议
        props.setProperty("mail.transport.protocol", "smtp");
        //设置发件人的SMTP服务器地址
        props.setProperty("mail.smtp.host", "smtp.163.com");
        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
            // 用户名、密码
            return new PasswordAuthentication(SENDER_ADDRESS, SENDER_PWD);
            }
        };
        return Session.getInstance(props, authenticator);
    }

    public static void main(String[] args) throws Exception {
        sendEmail(Arrays.asList("[email protected]", "[email protected]"), "我是标题", "我是内容", null);
    }

}

转载带地址,谢谢!

对你有帮助的话,右上角给个赞呗~

发布了61 篇原创文章 · 获赞 90 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/wkh___/article/details/93873685