Search code examples
outlookoffice365apioutlook-restapioffice365-restapi

How to properly respond to an email using the Outlook REST API


I am using the Outlook REST API. When responding, I create reply or replyall message following these instructions.

In my client app, some properties are updated, like the Body and the message can be sent. I want my end-users to have access to the previous message when responding (like many mail client). Consequently, I added an <hr tabindex="-1" style="display:inline-block; width: 98 %"> tag and then I insert the previous mail Body.Content.

My problem lies in the fact that the UniqueBody property is not writable. Outlook does not manage to recognize the previous email part in this newly created item. In other words UniqueBody and Body contain the same thing, the response and the original message. How can properly have those properties well set?


Solution

  • When you use /createreply, /createreplyall, or /createforward on a message, the API generates a draft message in the Drafts folder, and it copies a number of properties from the original message into this draft. For example, it may copy the subject and prepend a "RE:" to it, that sort of thing.

    For the body, it generates a horizontal line and an information summary (the "From", "Sent", "To", etc. that we're all familiar with). Then it adds the body of the original message underneath.

    Immediately after creation, the Body property of the draft reply/forward will contain all of these elements. The message that you want to add (the actual reply content) SHOULD go immediately before all of this content. If you follow that rule, the server can usually determine which part is the "unique" body and set UniqueBody accordingly.

    The key thing here is that you SHOULD NOT take the body from the original message and add it to your new text. Take the body from the draft message instead. That way you have the horizontal rule and the info summary in the exact format the server expects.

    Plain Text

    If the body of the draft reply/forward is plain text (i.e. { "Body": {"ContentType": "Text", "Content": "..." }}), then it's fairly straightforward. Generate the body like:

    var newBody = 'This is my response to your message.' + draftReply.Body.Content;
    
    var patchPayload = {
      'Body': { 
        'ContentType': 'Text',
        'Content': newBody
      }
    };
    

    HTML

    If the body of the draft reply/forward is HTML, it's only a little more complex. While you can load the HTML and essentially prepend your new content right after the <body> tag, you can simplify things a bit by creating your reply as a separate HTML document.

    var newBody = `<html><body><div>This is my response to your message.</div></body></html>` + draftReply.Body.Content;
    
    var patchPayload = {
      'Body': { 
        'ContentType': 'HTML',
        'Content': newBody
      }
    };