简单的java mail邮件群发系统

343 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

邮件用户验证类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
 
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
 
/**
 * Created by tarzan liu on 2020/5/9.
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class EmailAuthenticator extends Authenticator {
 
    private String username;
 
    private String password;
 
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
}
 

迷你邮件系统类

import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
 
/**
 * Created by tarzan liu on 2020/5/9.
 */
public class MicroEmailSystem {
 
    private static Session session = null;
 
    private static EmailAuthenticator authenticator = null;
 
    static {
            Properties properties = new Properties();
            authenticator = new EmailAuthenticator();
           //邮箱号
            authenticator.setUsername("######@163.com");
            //网易邮箱SMTP服务的授权嘛
            authenticator.setPassword("NSYEAUTYZRNRGXAZ");
            String smtpHostName = "smtp." + authenticator.getUsername().split("@")[1];
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.host", smtpHostName);
            session = Session.getInstance(properties, authenticator);
    }
 
 
    /**
     * 通用发邮件方法
     */
    private static void send(List<String> recipients, SimpleEmail email) throws MessagingException {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(authenticator.getUsername()));
        InternetAddress[] addresses = new InternetAddress[recipients.size()];
        for (int index = 0; index < recipients.size(); index ++) {
            addresses[index] = new InternetAddress(recipients.get(index));
        }
        message.setRecipients(RecipientType.TO, addresses);
        message.setSubject(email.getSubject());
        message.setContent(email.getContent(), "text/html;charset=utf-8");
        Transport.send(message);
    }
 
    /**
     * 群发邮件
     */
    public static void massSend(List<String> recipients, SimpleEmail email) throws MessagingException {
        send(recipients, email);
    }
 
   //测试主方法
    public static void main(String[] args) throws Exception {
        SimpleEmail simpleEmail = new SimpleEmail();
        simpleEmail.setSubject("你好吗?");
        simpleEmail.setContent("今天你写博客了么");
 
        List<String> recipients = new ArrayList<String>();
        recipients.add("tarzan0920@163.com");
 
        massSend(recipients, simpleEmail);
    }
}