0

是否可以使用 Java 发送电子邮件,以便我可以在 to/cc/bcc 字段中看到多个收件人?

换句话说,是这样的:

From: foo@bar.com
To: user1@lol.com; user2@lol.com; user3@lol.com; user4@lol.com
Cc: admin1@lol.com; admin2@lol.com

我在谷歌上搜索,但没有找到确凿的结果,所以任何建议都将不胜感激。

4

2 回答 2

1

是的!查看javax.mail 库

这是一个代码示例:

class EmailSender{
private Properties properties;
private Session session;
private Message msg;
private final String SENDER_EMAIL  = "your.email@whatever.com";
private final String PWD = "***********";

public void sendMail(String body) throws Throwable{
    initMail();
    msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress("SENDER_EMAIL"));
    //HERE YOU CAN CHOOSE BETWEEN TO, CC & BCC
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress("Receiver Email"));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress("Receiver Email2"));
    msg.setRecipient(Message.RecipientType.CC, new InternetAddress("CC Email"));
    msg.setRecipient(Message.RecipientType.CC, new InternetAddress("CC Email2"));

    msg.setSubject("SUBJECT");
    msg.setText(body);

    //TRANSPORT
    Transport.send(msg);
    System.out.println("message sent!");
}

private void initMail(){
    //PROPERTIES
   //I choosed GMAIL for the demonstration, but you cant choose whatever you want.
    properties = new Properties(); 
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", "587");


    //AUTHENTICATION
    session = Session.getInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(SENDER_EMAIL, PWD);
        }
    });
}

}

不要忘记导入javax.activation 库

于 2019-08-13T10:58:15.377 回答
0

是的。
怎么做 - 取决于您使用的库。

于 2013-08-13T09:33:51.783 回答