Send Mail to multiple Recipients in java

后端 未结 12 726
孤城傲影
孤城傲影 2020-12-02 08:23

I want to send a message to multiple Recipients using following the method :

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

<

相关标签:
12条回答
  • 2020-12-02 08:55

    Internet E-mail address format (RFC 822)

    (,)comma separated sequence of addresses

    javax.mail - 1.4.7 parse( String[] ) is not allowed. So we have to give comma separated sequence of addresses into InternetAddress objects. Addresses must follow RFC822 syntax.

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

    (;) semi-colon separated sequence of addresses « If group of address list is provided with delimeter as ";" then convert to String array using split method to use the following function.

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

    Full Example:

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

    Using Appache SimpleEmail - commons-email-1.3.1

    Example: 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!");
    }
    
    0 讨论(0)
  • 2020-12-02 08:57

    InternetAddress.Parse is going to be your friend! See the worked example below:

    String to = "med@joe.com, maz@frank.com, jezz@jam.com";
    String toCommaAndSpaces = "med@joe.com maz@frank.com, jezz@jam.com";
    
    1. Parse a comma-separated list of email addresses. Be strict. Require comma separated list.
    2. If strict is true, many (but not all) of the RFC822 syntax rules for emails are enforced.

      msg.setRecipients(Message.RecipientType.CC,
      InternetAddress.parse(to, true));
      
    3. Parse comma/space-separated list. Cut some slack. We allow spaces seperated list as well, plus invalid email formats.

      msg.setRecipients(Message.RecipientType.BCC,
      InternetAddress.parse(toCommaAndSpaces, false));
      
    0 讨论(0)
  • 2020-12-02 08:57

    You can use n-number of recipient below method:

      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);
    
    0 讨论(0)
  • 2020-12-02 08:58

    Hi every one this code is workin for me please try with this for sending mail to multiple recepients

    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);
    
    0 讨论(0)
  • 2020-12-02 09:03

    So ... it took many months, but still ... You can send email to multiple recipients by using the ',' as separator and

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

    is ok. At least in JavaMail 1.4.5

    0 讨论(0)
  • 2020-12-02 09:06

    You can have multiple addresses separated by comma

    if (cc.indexOf(',') > 0)
        message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));   
    else
        message.setRecipient(Message.RecipientType.CC, new InternetAddress(cc));
    
    0 讨论(0)
提交回复
热议问题