Sending email using EWS in c# from shared mailbox

Kuni picture Kuni · Jun 19, 2017 · Viewed 7.8k times · Source

The IT department is moving away from creating a service account to shared mailbox. All of our department email accounts are being converted to shared mailbox. Until now, I had been using EWS to send email from our web app to recipients using the following code:

ExchangeService service = new ExchangeService();
service = new ExchangeService(ExchangeVersion.Exchange2013_SP1)
{
     Credentials = new NetworkCredential("[email protected]", "Password1"),
     Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx")
            };

     email = new EmailMessage(service);
     email.Body = new MessageBody(BodyType.HTML, Message.ToString());
     email.ToRecipients.Add(Recipient.email);
     email.SendAndSaveCopy();
}

How can I use shared mailbox for sending emails instead of having hard coding email address and password? The email address I use is the service account that doesn't fall in the current password security criteria. It is because of this reason, they're changing department emails to shared mailbox.

I'm using Windows Authentication that authenticates users from Active Directory.

Answer

Glen Scales picture Glen Scales · Jun 20, 2017

If you want to keep using EWS you will still probably need a Service account for using Shared Mailboxes (unless your app can impersonate a user that has SendAS rights on the Shared Mailbox), eg your grant the Service Account SendAs rights for the Shared Mailboxes you want to send as and then Set the From Address and Sent Items Folder to that of the Shared Mailbox (that's if you want a copy of the message saved in the Shared Mailboxes Sent Items Folder). eg

        email.From = new EmailAddress("[email protected]"); 
        Mailbox SharedMailbox = new Mailbox("[email protected]");
        FolderId SharedMailboxSendItems = new FolderId(WellKnownFolderName.SentItems, SharedMailbox);
        email.SendAndSaveCopy(SharedMailboxSendItems);

A better approach which would allow you to get rid of the service account would be to use the new REST API https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations then create an App that just has rights to Send Email and take advantage of certificate authentication https://msdn.microsoft.com/en-us/office/office365/howto/building-service-apps-in-office-365. That should allow you to get rid of any licences requirements for the Service Account and also gives a much more secure application as you no longer have hardcoded creds and your app just has access for what it needs to to do and nothing else.