2

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!

Matt F
  • 129
  • 1
  • 8

2 Answers2

3

I've also been trying to use the SendMailAsync method of the OutlookServicesClient and have received the Unauthorized response.

Fiddler revealed that the token is not included in the request created by SendMailAsync, however I can see that the token is included when OutlookServicesClient generates a Get request to read messages. This was confirmed for me by this GitHub issue which also stated that it used to work in version 1.0.22 of the library but not since version 1.0.34.

After looking around some more I found that others have tried an alternative approach to sending mail by first creating a draft, and then sending it. Here is what this looks like:

OutlookServicesClient outlookClient = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"),
    async () =>
    {
        // already retrieved my AccessToken using AuthenticationContext
        return AccessToken;
    });

// Save to Drafts folder
await outlookClient.Me.Messages.AddMessageAsync(newMessage);

// Now send
await newMessage.SendAsync();

My conclusion is that the SendMailAsync method is simply broken. By first saving the new message as a draft we can work around it.

Community
  • 1
  • 1
Dean
  • 4,554
  • 7
  • 34
  • 45
  • Excellent, thank you - it's working using the draft method. As far as I remember the 365 API is in Preview so hopefully it's something that will be corrected on their side soon. – Matt F Jan 06 '16 at 11:14
1

Check your token value. If you copy the string and go over to http://jwt.calebb.net/, you can paste it in and have it parsed out. Check the scp claim and make sure Mail.Send is there.

Jason Johnston
  • 17,194
  • 2
  • 20
  • 34
  • Hi Jason, thanks for the link - I tested it and it looks ok to me, this is the scp part: scp: "Mail.ReadWrite Mail.Send", – Matt F Dec 18 '15 at 17:16
  • Can you get a Fiddler trace of the request and see what's being sent over the wire? Make sure the right token value is being sent in the Authorize header. – Jason Johnston Dec 18 '15 at 17:26
  • Hi Jason, I have just tried Fiddler but it doesn't seem to be showing the part where I am attempting to connect to Office 365 (unless I need to configure something on it so it will show?). So when I am in my asp mvc app, in the email form I click a 'Send Email' button which directs to a controller action, this action builds up the message details and then calls the SendMailAsync function. The last thing that comes up in Fiddler is the call to the action in my controller and then nothing else after that – Matt F Dec 21 '15 at 15:29
  • @MattF, make sure you have Fiddler configured to decrypt https traffic. In Fiddler go to Tools -> Fiddler Options -> HTTPS and tick the appropriate boxes. You may need to restart for it to take affect. – Dean Jan 05 '16 at 19:52