Javamail发送邮件

1.添加Maven依赖
 <dependency>
  <groupId>javax.mail</groupId>
  <artifactId>mail</artifactId>
  <version>1.4</version>
</dependency>
<dependency>
  <groupId>javax.activation</groupId>
  <artifactId>activation</artifactId>
  <version>1.1</version>
</dependency>
2.创建email.properties,设置发邮件邮箱的用户名密码
email.username=
email.password=
3.添加EmailAuthenticator继承Authenticator
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class EmailAuthenticator extends Authenticator {

    private String username;

    private String password;

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
}
4.创建EmailUtil工具类
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

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;

public abstract class EmailUtil {

    private static Session session = null;

    private static EmailAuthenticator authenticator = null;

    static {
        try {
            InputStream inputStream = EmailUtil.class.getResourceAsStream("/email.properties");
            Properties properties = new Properties();
            properties.load(inputStream);

            authenticator = new EmailAuthenticator();
            String username = properties.getProperty("email.username");
            authenticator.setUsername(username);

            String password = properties.getProperty("email.password");
            authenticator.setPassword(password);

            String smtpHostName = "smtp." + username.split("@")[1];
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.host", smtpHostName);

            session = Session.getInstance(properties, authenticator);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private EmailUtil() { }

    /**
     * 通用发邮件方法
     */
    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 send(String recipient, SimpleEmail email) throws MessagingException {
        List<String> recipients = new ArrayList<String>();
        recipients.add(recipient);
        send(recipients, email);
    }

    /**
     * 群发邮件
     */
    public static void massSend(List<String> recipients, SimpleEmail email) throws MessagingException {
        send(recipients, email);
    }
}
5.测试
public static void main(String[] args) throws Exception {
    SimpleEmail simpleEmail = new SimpleEmail();
    simpleEmail.setSubject("今天你学习了么?");
    simpleEmail.setContent("今天你写博客了么");

    List<String> recipients = new ArrayList<String>();
    recipients.add("2668659188@qq.com");

    massSend(recipients, simpleEmail);
}

代码地址:https://gitee.com/jsjack_wang/JavaDemo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,713评论 19 139
  • JavaMail是SUN提供给广大Java开发人员的一款邮件发送和接受的一款开源类库,支持常用的邮件协议,如:SM...
    恒宇少年阅读 26,476评论 26 42
  • ‌细雨斜阳瑟,雁阵过,骨寒彻。添灯去薄衾,执笔着墨色。天寒多几缕白霜,昨日欢笑寻何处。相思愁肠似入蛊,盼君归来,解...
    聆听大海的呱声阅读 1,202评论 0 0
  • 文/唐培蕊 Pray 小茗和她的男友,跟我在同一家医院实习,但是因为是在不同的科室,所以两人见面的机会并不多,活生...
    ENT_Pray阅读 3,318评论 0 2
  • 前天,我在城里工地的一角 捡到一块残缺不全的瓦片 它和生活垃圾丢在一起 望着它 我不由想到了父亲 我的父亲,进城打...
    H细泉阅读 1,859评论 4 7