Search code examples
javamicrosoft-exchange

Multiple Recipients using Microsoft exchange


I was Success to sending email using Microsoft exchange, but it just 1 Recipient. I want to try send multiple Recipients.

ExchangeService service = new ExchangeService();
    WebCredentials webCredentials = new WebCredentials("xxx", "xxx", "xxx");
    service.setCredentials((ExchangeCredentials) webCredentials);
    service.setUrl(new URI("https://webmail.com"));
    try {
        StringBuilder strBldr = new StringBuilder();
        strBldr.append(converStringToUrlDecoded(bodyMail));
        EmailMessage message = new EmailMessage(service);
        message.setSubject(converStringToUrlDecoded(subject));
        message.setBody(new MessageBody(strBldr.toString()));
        message.getToRecipients().add(recipientsList);
        message.setIsDeliveryReceiptRequested(Boolean.valueOf(true));
        message.sendAndSaveCopy();
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("message sent");

This is my code with single recipient.


Solution

  • If you have an array of recipients you should be able to loop that array and call the .add every time. If getToRecipient implements .addrange then you should be able to just pass the array to .addrange.

    You can try this:

    ExchangeService service = new ExchangeService();
    WebCredentials webCredentials = new WebCredentials("xxx", "xxx", "xxx");
    service.setCredentials((ExchangeCredentials) webCredentials);
    service.setUrl(new URI("https://webmail.com"));
    try {
        StringBuilder strBldr = new StringBuilder();
        strBldr.append(converStringToUrlDecoded(bodyMail));
        EmailMessage message = new EmailMessage(service);
        message.setSubject(converStringToUrlDecoded(subject));
        message.setBody(new MessageBody(strBldr.toString()));
    
        foreach(var r in recipientsList){
            message.getToRecipients().add(r);
        }
            
        message.setIsDeliveryReceiptRequested(Boolean.valueOf(true));
        message.sendAndSaveCopy();
    } 
    catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("message sent");
    

    Optionally if message.getToRecipients() implements the AddRange() method try this (replace the foreach loop with below):

    message.getToRecipients().addRange(recipientsList);