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

问题描述 投票:71回答:12

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

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

要么

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

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

message.addRecipient(Message.RecipientType.CC, "[email protected],[email protected],[email protected]");

要么

message.addRecipient(Message.RecipientType.CC, "[email protected];[email protected];[email protected]");

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

java javamail
12个回答
104
投票

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

例如:

message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("[email protected]"));
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("[email protected]"));
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("[email protected]"));

将3个地址添加到CC


如果您希望一次添加所有地址,您应该使用setRecipientsaddRecipients并为其提供一组地址

Address[] cc = new Address[] {InternetAddress.parse("[email protected]"),
                               InternetAddress.parse("[email protected]"), 
                               InternetAddress.parse("[email protected]")};
message.addRecipients(Message.RecipientType.CC, cc);

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

message.addRecipients(Message.RecipientType.CC, 
                      InternetAddress.parse("[email protected],[email protected],[email protected]"));

1
投票

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

commons-email-1.3.1

1
投票

如果你想使用MimeMessageHelper作为Cc发送

email.addTo( addressList );

您可以使用相同的方式添加多个收件人。


0
投票

简单的方法

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( "[email protected]", "Yash" );
    String[] toAddressList = { "[email protected]", "[email protected]" }
    email.addTo( addressList );

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

26
投票

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

private String recipient = "[email protected] ,[email protected] ";
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("[email protected]"));
String address = "[email protected],[email protected]";
InternetAddress[] iAdressArray = InternetAddress.parse(address);
message.setRecipients(Message.RecipientType.CC, iAdressArray);

11
投票

只需使用带有逗号分隔的多个地址的message.setRecipients方法:

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected],[email protected],[email protected]"));

message.setRecipients(Message.RecipientType.CC, InternetAddress.parse("[email protected],[email protected],[email protected]"));

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

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));

11
投票

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

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

5
投票

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

message.setRecipients(Message.RecipientType.CC, "[email protected],[email protected],[email protected]");

没关系。至少在JavaMail 1.4.5中


5
投票

InternetAddress.Parse将成为你的朋友!请参阅下面的工作示例:

String to = "[email protected], [email protected], [email protected]";
String toCommaAndSpaces = "[email protected] [email protected], [email protected]";
  1. 解析以逗号分隔的电子邮件地址列表。要严格。需要以逗号分隔的列表。
  2. 如果严格为真,则强制执行电子邮件的许多(但不是全部)RFC822语法规则。 msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, true));
  3. 解析逗号/空格分隔列表。削减一些懈怠。我们也允许空格分隔列表,以及无效的电子邮件格式。 qazxsw poi

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

2
投票

互联网电子邮件地址格式(String[] mailAddressTo = new String[3]; mailAddressTo[0] = emailId_1; mailAddressTo[1] = emailId_2; mailAddressTo[2] = "[email protected]"; 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];

RFC 822comma分开的地址序列

javax.mail - 1.4.7不允许使用(,)。所以我们必须将逗号分隔的地址序列放入parse( String[] )对象中。地址必须遵循RFC822语法。

InternetAddress

String toAddress = "[email protected],[email protected]"; InternetAddress.parse( toAddress ); 分号分隔的地址序列«如果(;)提供的分隔符为“;”然后使用split方法转换为String数组以使用以下函数。

group of address list
String[] addressList = { "[email protected]", "[email protected]" };

String toGroup = "[email protected];[email protected]";
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);
    }
}

使用Apache qazxsw poi - qazxsw poi

示例: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(); }

SimpleEmail
© www.soinside.com 2019 - 2024. All rights reserved.