【问题标题】:Send Mail to multiple Recipients in java在java中向多个收件人发送邮件
【发布时间】:2012-11-30 23:59:57
【问题描述】:

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

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

【问题讨论】:

    标签: java jakarta-mail


    【解决方案1】:

    如果您多次调用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个地址添加到抄送


    如果您希望一次添加所有地址,您应该使用 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"));
    

    【讨论】:

    • 其实我的问题是专门针对特定方法的。
    • 您可以将addRecipient/setRecipient 与单个地址一起使用,或者将addRecipients/setRecipients 与一组地址一起使用
    • javax.mail 1.5.5 版没有返回StringInternetAddress.parse()。所有解析方法都返回数组,因此不适用于addRecipient。有没有其他版本有这种方法?
    • 当你有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] 应该应用于每个解决方案中的所有地址。
    • @luke.. 谢谢,我已经挣扎了一段时间.. 你的评论帮助了我。
    【解决方案2】:

    大家好,此代码对我有用,请尝试使用此代码向多个收件人发送邮件

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

    【讨论】:

      【解决方案3】:

      只需使用多个地址用逗号分隔的方法 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】:

        试试这个方法:

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

        【讨论】:

          【解决方案5】:

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

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

          【讨论】:

          • 你为什么不同时使用InternetAddress.parse() 呢? (是的,我知道这是 4 岁)
          • @seanbright 是的,您可以让第一条语句完全跳过 if else 条件。 setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc)); 应该可以工作,即使只有 1 个地址。这只是一种提高可读性的个人编程方式。
          【解决方案6】:

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

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

          【讨论】:

            【解决方案7】:

            所以...花了几个月的时间,但仍然...您可以使用“,”作为分隔符和

            向多个收件人发送电子邮件
            message.setRecipients(Message.RecipientType.CC, "abc@abc.com,abc@def.com,ghi@abc.com");
            

            没问题。至少在 JavaMail 1.4.5 中

            【讨论】:

              【解决方案8】:

              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 为真,则会强制执行许多(但不是全部)电子邮件的 RFC822 语法规则。

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

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

              【讨论】:

                【解决方案9】:
                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]; 
                

                【讨论】:

                  【解决方案10】:

                  简单的方法

                  String[] listofIDS={"ramasamygms@gmail.com","ramasamycse94@gmail.com"};
                  
                  for(String cc:listofIDS) {
                      message.addRecipients(Message.RecipientType.CC,InternetAddress.parse(cc));
                  }
                  

                  【讨论】:

                    【解决方案11】:

                    您可以使用以下方法的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);
                    

                    【讨论】:

                    • 我在我的问题中指定了一个特定的方法,想用那个方法发送。
                    • @Dhinkar,如何使用 java 向所有订阅者发送邮件?
                    【解决方案12】:

                    如果您想使用 MimeMessageHelper 作为抄送发送

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

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

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 2015-10-21
                      • 1970-01-01
                      • 2020-09-15
                      • 1970-01-01
                      • 2012-05-18
                      • 2012-03-22
                      相关资源
                      最近更新 更多