集册 Java实例教程 发送邮件

发送邮件

—— 发送E

欢马劈雪     最近更新时间:2020-01-02 10:19:05

422
将电子邮件发送给一组收件人

import java.util.ArrayList;

import java.util.List;
/*来自 
 n o w j a v a . c o m*/

import java.util.Properties;


import javax.mail.Address;

import javax.mail.Authenticator;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.AddressException;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;


public class Main {

  public static void main(String[] args) {

    List<String> emails = new ArrayList<>();

    emails.add("j@nowjava.com");

    emails.add("b@nowjava.com");// from nowjava.com - 时代Java

    emails.add("w@nowjava.com");

    Properties properties = new Properties();

    properties.put("mail.smtp.host", "smtp.somewhere.com");

    properties.put("mail.smtp.auth", "true");


    Session session = Session.getDefaultInstance(properties,

        new MessageAuthenticator("username", "password"));


    Message message = new MimeMessage(session);

    try {

      message.setFrom(new InternetAddress("someone@somewhere.com"));

      message.setRecipients(Message.RecipientType.BCC, getRecipients(emails));

      message.setSubject("Subject");

      message.setContent("This is a test message", "text/plain");

      Transport.send(message);

    } catch (MessagingException e) {

      e.printStackTrace();

    }

  }


  private static Address[] getRecipients(List<String> emails)

      throws AddressException {

    Address[] addresses = new Address[emails.size()];

    for (int i = 0; i < emails.size(); i++) {

      addresses[i] = new InternetAddress(emails.get(i));

    }

    return addresses;

  }

}


展开阅读全文