I am trying to set up Office 365 integration from my ASP MVC web app in C#, for which I am using the Outlook Mail REST API (client version). I've been using the API reference here: https://msdn.microsoft.com/office/office365/APi/mail-rest-operations
I can log in to Office 365 fine, and get the token and then read mail folders (i.e. Sent Items / Inbox) but when I try to send an email I get the following error:
Unauthorized
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Microsoft.OData.Client.DataServiceClientException: Unauthorized
I've added the permissions to read/write and send emails, so when I log into Office 365 it says:
Office Integration Test App needs permission to:
Access your data anytime
Sign in as you
Send mail as you
Read and write access to your mail
So I presume the 'Send mail as you' is the one I need. However I am still getting the Unathorized error message.
Here is the code I'm running to send the email:
string AccessToken = (string)Session["Office365Token"];
OutlookServicesClient client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"),
async () =>
{
return AccessToken;
});
ItemBody EmailBody = new ItemBody
{
Content = "Test email from the project",
ContentType = BodyType.HTML
};
List<Recipient> toRecipients = new List<Recipient>();
toRecipients.Add(new Recipient() { EmailAddress = new EmailAddress() { Address = "testemail@test.com" } });
Message newMessage = new Message
{
Subject = "Test Subject For Email",
Body = EmailBody,
ToRecipients = toRecipients
};
await client.Me.SendMailAsync(newMessage, true);
The error happens on the last line when I'm calling SendMailAsync. I'm not really sure what else to try and can't find any info about what would cause this.
Any help is greatly appreciated!