使用Java将邮件发送给多个收件人


80

我想使用以下方法将消息发送给多个收件人:

message.addRecipient(Message.RecipientType.TO, String arg1);

要么

message.setRecipients(Message.RecipientType.TO,String arg1);

但一个困惑是,在第二点争论中,如何传递多个地址,例如:

message.addRecipient(Message.RecipientType.CC, "abc@abc.com,abc@def.com,ghi@abc.com");

要么

message.addRecipient(Message.RecipientType.CC, "abc@abc.com;abc@def.com;ghi@abc.com");

我也可以使用其他方法发送消息,但是想知道上述方法的目的。如果我不能使用它(到目前为止,我对上述要求还没有任何答案),那么在邮件API中使用此方法有什么要求。

Answers:


113

如果您addRecipient多次调用,它将把给定的收件人添加到给定时间的收件人列表(TO,CC,BCC)

例如:

message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("abc@abc.com"));
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("abc@def.com"));
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("ghi@abc.com"));

将3个地址添加到CC


如果您希望一次添加所有地址,则应使用setRecipientsaddRecipients为它提供地址数组

Address[] cc = new Address[] {InternetAddress.parse("abc@abc.com"),
                               InternetAddress.parse("abc@def.com"), 
                               InternetAddress.parse("ghi@abc.com")};
message.addRecipients(Message.RecipientType.CC, cc);

您还可以使用InternetAddress.parse解析地址列表

message.addRecipients(Message.RecipientType.CC, 
                      InternetAddress.parse("abc@abc.com,abc@def.com,ghi@abc.com"));

1
实际上,我的问题是专门针对特定方法的。
Prateek

2
您要么使用addRecipient/setRecipient使用单个地址,要么addRecipients/setRecipients使用地址数组
Aviram Segal 2012年

3
javax.mail1.5.5版本没有InternetAddress.parse()返回String。所有解析方法都返回array,因此不适合addRecipient。是否有其他版本具有这种方法?
yurin

2
当你有javax.mail版本1.5.5或更高,其中不必InternetAddress.parse()回返单个InternetAddress但只有一个返回InternetAddress[](阵列),则可以使用第一溶液具有 ... message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("abc@def.com")[0]); ... ([0]有很重要)。在第二个解决方案中: ... new Address[] {InternetAddress.parse("abc@abc.com")[0], ... 第三个解决方案应该可以正常工作。当然,末尾的[0]应该应用于每个解决方案中的所有地址。
路加福音

1
@luke ..谢谢,我已经挣扎了一段时间..您的评论对我有所帮助。
stack0114106

29

大家好,此代码对我有用,请尝试将其发送给多个收件人

private String recipient = "yamabs@gmail.com ,priya@gmail.com ";
String[] recipientList = recipient.split(",");
InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
int counter = 0;
for (String recipient : recipientList) {
    recipientAddress[counter] = new InternetAddress(recipient.trim());
    counter++;
}
message.setRecipients(Message.RecipientType.TO, recipientAddress);

12

尝试这种方式:

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("mail3@mail.com"));
String address = "mail@mail.com,mail2@mail.com";
InternetAddress[] iAdressArray = InternetAddress.parse(address);
message.setRecipients(Message.RecipientType.CC, iAdressArray);

12

只需使用message.setRecipients方法,将多个地址用逗号分隔即可:

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("abc@abc.com,abc@def.com,ghi@abc.com"));

message.setRecipients(Message.RecipientType.CC, InternetAddress.parse("abc@abc.com,abc@def.com,ghi@abc.com"));

仅使用一个地址也可以正常工作

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("abc@abc.com"));

11

您可以使用逗号分隔多个地址

if (cc.indexOf(',') > 0)
    message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));   
else
    message.setRecipient(Message.RecipientType.CC, new InternetAddress(cc));

1
您为什么不InternetAddress.parse()同时使用两者?(是的,我知道这是4岁了)
肖恩·布莱特

2
@seanbright是的,您可以让第一条语句完全跳过if else条件。setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));即使只有1个地址,也应能正常工作。这只是增加可读性的一种个人编程方式。
ThePCWizard's

6

所以...花了很多月,但仍然...您可以使用','作为分隔符,将电子邮件发送给多个收件人

message.setRecipients(Message.RecipientType.CC, "abc@abc.com,abc@def.com,ghi@abc.com");

还可以 至少在JavaMail 1.4.5中


5

InternetAddress.Parse将成为您的朋友!请参见下面的示例:

String to = "med@joe.com, maz@frank.com, jezz@jam.com";
String toCommaAndSpaces = "med@joe.com maz@frank.com, jezz@jam.com";
  1. 解析以逗号分隔的电子邮件地址列表。严格一点 需要逗号分隔的列表。
  2. 如果strict为true,则对电子邮件执行许多(但不是全部)RFC822语法规则。

    msg.setRecipients(Message.RecipientType.CC,
    InternetAddress.parse(to, true));
    
  3. 解析逗号/以空格分隔的列表。减少一些懈怠。我们也允许使用空格分隔列表,以及无效的电子邮件格式。

    msg.setRecipients(Message.RecipientType.BCC,
    InternetAddress.parse(toCommaAndSpaces, false));
    

4
String[] mailAddressTo = new String[3];    
mailAddressTo[0] = emailId_1;    
mailAddressTo[1] = emailId_2;    
mailAddressTo[2] = "xyz@gmail.com";

InternetAddress[] mailAddress_TO = new InternetAddress[mailAddressTo.length];

for (int i = 0; i < mailAddressTo.length; i++)
{
    mailAddress_TO[i] = new InternetAddress(mailAddressTo[i]);
}

message.addRecipients(Message.RecipientType.TO, mailAddress_TO);ress_TO = new InternetAddress[mailAddressTo.length]; 

3

Internet电子邮件地址格式(RFC 822

(,)逗号分隔的地址序列

javax.mail-parse( String[] )不允许1.4.7 。因此,我们必须将逗号分隔的地址序列赋予InternetAddress对象。地址必须遵循RFC822语法。

String toAddress = "mail@mail.com,mail2@mail.com";
InternetAddress.parse( toAddress );

(;)用分号分隔的地址序列«如果地址列表组的分隔符为“;” 然后使用split方法转换为String数组以使用以下函数。

String[] addressList = { "mail@mail.com", "mail2@mail.com" };

String toGroup = "mail@mail.com;mail2@mail.com";
String[] addressList2 = toGroup.split(";");

setRecipients(message, addressList);
public static void setRecipients(Message message, Object addresslist) throws AddressException, MessagingException {
    if ( addresslist instanceof String ) { // CharSequence
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse( (String) addresslist  ));
    } else if ( addresslist instanceof String[] ) { // String[] « Array with collection of Strings/
        String[] toAddressList = (String[]) addresslist;
        InternetAddress[] mailAddress_TO = new InternetAddress[ toAddressList.length ];
        for (int i = 0; i < toAddressList.length; i++) {
            mailAddress_TO[i] = new InternetAddress( toAddressList[i] );
        }
        message.setRecipients(Message.RecipientType.TO, mailAddress_TO);
    }
}

完整示例:

public static Properties getMailProperties( boolean addExteraProps ) {
    Properties props = new Properties();
    props.put("mail.transport.protocol", MAIL_TRNSPORT_PROTOCOL);
    props.put("mail.smtp.host", MAIL_SERVER_NAME);
    props.put("mail.smtp.port", MAIL_PORT);

    // Sending Email to the GMail SMTP server requires authentication and SSL.
    props.put("mail.smtp.auth", true);
    if( ENCRYPTION_METHOD.equals("STARTTLS") ) {
        props.put("mail.smtp.starttls.enable", true);
        props.put("mail.smtp.socketFactory.port", SMTP_STARTTLS_PORT); // 587
    } else {
        props.put("mail.smtps.ssl.enable", true);
        props.put("mail.smtp.socketFactory.port", SMTP_SSL_PORT); // 465
    }
    props.put("mail.smtp.socketFactory", SOCKETFACTORY_CLASS);
    return props;
}

public static boolean sendMail(String subject, String contentType, String msg, Object recipients) throws Exception {

    Properties props = getMailProperties( false );
    Session mailSession = Session.getInstance(props, null);
    mailSession.setDebug(true);

    Message message = new MimeMessage( mailSession );
    message.setFrom( new InternetAddress( USER_NAME ) );

    setRecipients(message, recipients);

    message.setSubject( subject );

    String htmlData = "<h1>This is actual message embedded in HTML tags</h1>";
    message.setContent( htmlData, "text/html");

    Transport transport = mailSession.getTransport( MAIL_TRNSPORT_PROTOCOL );
    transport.connect(MAIL_SERVER_NAME, Integer.valueOf(MAIL_PORT), USER_NAME, PASSWORD);
    message.saveChanges(); // don't forget this

    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

使用Appache SimpleEmail-commons-email-1.3.1

例: email.addTo( addressList );

public static void sendSimpleMail() throws Exception {
    Email email = new SimpleEmail();
    email.setSmtpPort(587);

    DefaultAuthenticator defaultAuthenticator = new DefaultAuthenticator( USER_NAME, PASSWORD );

    email.setAuthenticator( defaultAuthenticator );
    email.setDebug(false);
    email.setHostName( MAIL_SERVER_NAME );
    email.setFrom( USER_NAME );
    email.setSubject("Hi");
    email.setMsg("This is a test mail ... :-)");

    //email.addTo( "mail@mail.com", "Yash" );
    String[] toAddressList = { "mail@mail.com", "mail2@mail.com" }
    email.addTo( addressList );

    email.setTLS(true);
    email.setStartTLSEnabled( true );
    email.send();
    System.out.println("Mail sent!");
}

1

您可以使用以下方法使用n个收件人:

  String to[] = {"a@gmail.com"} //Mail id you want to send;
  InternetAddress[] address = new InternetAddress[to.length];
  for(int i =0; i< to.length; i++)
  {
      address[i] = new InternetAddress(to[i]);
  }

   msg.setRecipients(Message.RecipientType.TO, address);

我在我的问题中指定了一种特定的方法,希望使用该方法进行发送。
Prateek

1

如果要使用MimeMessageHelper作为抄送发送

List<String> emails= new ArrayList();
email.add("email1");
email.add("email2");
for (String string : emails) {
message.addCc(string);
}

可以用来添加多个收件人的相同。


1

简单的方法

String[] listofIDS={"ramasamygms@gmail.com","ramasamycse94@gmail.com"};

for(String cc:listofIDS) {
    message.addRecipients(Message.RecipientType.CC,InternetAddress.parse(cc));
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.