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

时间:2012-12-13 06:13:33

标签: java javamail

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

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中。

12 个答案:

答案 0 :(得分:103)

如果多次调用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 :(得分: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);

答案 2 :(得分:11)

尝试这种方式:

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);

答案 3 :(得分: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"));

只有一个地址也能正常工作

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

答案 4 :(得分:10)

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

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

答案 5 :(得分:5)

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

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

没问题。至少在JavaMail 1.4.5中

答案 6 :(得分: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));
    

答案 7 :(得分: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]; 

答案 8 :(得分:2)

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

  

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

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

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

(;)用分号分隔的地址序列«   如果group of address list的分隔符为“;”然后使用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();
}

  

使用方法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!");
}

答案 9 :(得分: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);

答案 10 :(得分:1)

如果您想使用MimeMessageHelper发送为Cc

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

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

答案 11 :(得分:0)

简便的方法

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

    for(String cc:listofIDS){
    message.addRecipients(Message.RecipientType.CC,InternetAddress.parse(cc));
    }
相关问题