Search code examples
javascriptoutlookoffice-jsoffice-addinsoutlook-web-addins

Office.js - get the email body content using getAsync and assign it to a variable


I am trying to get the body content of emails in Outlook using the body.getAsync() method:

let body = '';
body = Office.context.mailbox.item.body.getAsync(
   "text",
    function (result) {
        if (result.status === Office.AsyncResultStatus.Succeeded) {
            body = result.value;
        }
    }
);
console.log(body);

In this case, console.log(body) returns undefined. However, if I try to log the result inside the getAsync callback:

if (result.status === Office.AsyncResultStatus.Succeeded) {
      body = result.value;
      console.log(body);

}

It works fine, and the email body content is successfully returned.


Solution

  • You have to remember that Javascript runs synchronously from top to bottom unless you use callbacks, promises or async/await. Essentially, body is undefined because Office.context.mailbox.item.body.getAsync() has not completed when the console.log() is called. When getAsync() completes, then the callback function is called. Also, getAsync() returns void not the message body. You need to use the callback to access the body.

    What you could do is:

    let body = '';
    Office.context.mailbox.item.body.getAsync(
      "text",
      function (result) {
        if (result.status === Office.AsyncResultStatus.Succeeded) {
          body = result.value;
          doSomething(body)
        }
      }
    )
    
    function doSomething(body){
      console.log(body);
    }