是否可以使用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


我在Google上进行了搜索,但没有最终结果,因此,任何建议都将不胜感激。

最佳答案

是的!
查看javax.mail library

这是一个代码示例:

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 library

关于java - Java电子邮件-显示多个电子邮件收件人?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18205391/

10-11 22:30
查看更多