在Java中将邮件发送给多个收件人

Pra*_*eek 74 java jakarta-mail

我想使用以下方法向多个收件人发送邮件:

message.addRecipient(Message.RecipientType.TO, String arg1);
Run Code Online (Sandbox Code Playgroud)

要么

message.setRecipients(Message.RecipientType.TO,String arg1);
Run Code Online (Sandbox Code Playgroud)

但令人困惑的是,在第二个争论中,如何传递多个地址,如:

message.addRecipient(Message.RecipientType.CC, "abc@abc.com,abc@def.com,ghi@abc.com");
Run Code Online (Sandbox Code Playgroud)

要么

message.addRecipient(Message.RecipientType.CC, "abc@abc.com;abc@def.com;ghi@abc.com");
Run Code Online (Sandbox Code Playgroud)

我也可以使用替代方法发送消息,但想知道上述方法的目的.如果我不能使用它(因为直到现在我还没有得到上述要求的任何答案)那么这个方法需要在邮件API中.

Avi*_*gal 107

如果您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"));
Run Code Online (Sandbox Code Playgroud)

将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);
Run Code Online (Sandbox Code Playgroud)

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

message.addRecipients(Message.RecipientType.CC, 
                      InternetAddress.parse("abc@abc.com,abc@def.com,ghi@abc.com"));
Run Code Online (Sandbox Code Playgroud)

  • 更新了我的答案,以显示如何一次添加所有内容 (3认同)
  • `javax.mail`版本1.5.5没有返回`String`的`InternetAddress.parse()`.所有解析方法都返回数组,因此不适合`addRecipient`.是否有其他版本有这样的方法? (3认同)
  • 你可以使用带有单个地址的`addRecipient` /`setRecipient`或带有地址数组的`addRecipients` /`setRecipients` (2认同)
  • 如果您使用的Javax.mail版本为1.5.5或更高版本,而您没有返回单个InternetAddress的InternetAddress.parse(),但是仅返回InternetAddress [](数组)的那个,则您可以使用具有“ ... message.addRecipient(Message.RecipientType.CC,InternetAddress.parse(“ abc@def.com”)[0])的“第一个解决方案”;...`**([0]在这里很重要)**。在**第二种解决方案中:**`... new Address [] {InternetAddress.parse(“ abc@abc.com”)[0],...`**第三种解决方案**应该可以正常工作。当然,最后的** [0] **应该应用于每个解决方案中的所有地址。 (2认同)

小智 26

嗨,每一个这个代码都适合我,请尝试使用此发送邮件给多个接收者

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);
Run Code Online (Sandbox Code Playgroud)


小智 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);
Run Code Online (Sandbox Code Playgroud)


The*_*ard 11

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

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

  • @seanbright是的,你可以让第一个语句完全跳过if else条件.`setRecipients(Message.RecipientType.CC,InternetAddress.parse(cc));`即使只有一个地址也应该工作.这是一种提高可读性的个性化编程方式. (2认同)

小智 11

只需使用带有逗号分隔的多个地址的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"));
Run Code Online (Sandbox Code Playgroud)

只有一个地址也可以正常工作

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("abc@abc.com"));
Run Code Online (Sandbox Code Playgroud)


Yas*_*ash 7

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

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

javax.mail - 1.4.7parse( String[] )是不允许的。所以我们必须将逗号分隔的地址序列分配给InternetAddress对象。地址必须遵循 RFC822 语法。

String toAddress = "mail@mail.com,mail2@mail.com";
InternetAddress.parse( toAddress );
Run Code Online (Sandbox Code Playgroud)

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

String toAddress = "mail@mail.com,mail2@mail.com";
InternetAddress.parse( toAddress );
Run Code Online (Sandbox Code Playgroud)
String[] addressList = { "mail@mail.com", "mail2@mail.com" };

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

setRecipients(message, addressList);
Run Code Online (Sandbox Code Playgroud)

完整示例:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用 Appache SimpleEmail-commons-email-1.3.1

例子: email.addTo( addressList );

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();
}
Run Code Online (Sandbox Code Playgroud)


bes*_*s67 5

所以......花了好几个月,但仍然......你可以使用','作为分隔符,向多个收件人发送电子邮件

message.setRecipients(Message.RecipientType.CC, "abc@abc.com,abc@def.com,ghi@abc.com");
Run Code Online (Sandbox Code Playgroud)

没关系.至少在JavaMail 1.4.5中


Mat*_*att 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";
Run Code Online (Sandbox Code Playgroud)
  1. 解析以逗号分隔的电子邮件地址列表.要严格.需要以逗号分隔的列表.
  2. 如果strict为true,则强制执行许多(但不是全部)RFC822电子邮件语法规则.

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

    msg.setRecipients(Message.RecipientType.BCC,
    InternetAddress.parse(toCommaAndSpaces, false));
    
    Run Code Online (Sandbox Code Playgroud)