Office.Body interface
The body object provides methods for adding and updating the content of the message or appointment. It is returned in the body property of the selected item.
Remarks
Known issue with HTML table border colors
Outlook on Windows: If you're setting various cell borders to different colors in an HTML table in Compose mode, a cell's borders may not reflect the expected color. For the known behavior, visit OfficeDev/office-js issue #1818.
Minimum permission level: read item
Applicable Outlook mode: Compose or Read
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/20-item-body/add-inline-base64-image.yaml
const mailItem = Office.context.mailbox.item;
const base64String =
"iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAnUExURQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN0S+bUAAAAMdFJOUwAQIDBAUI+fr7/P7yEupu8AAAAJcEhZcwAADsMAAA7DAcdvqGQAAAF8SURBVGhD7dfLdoMwDEVR6Cspzf9/b20QYOthS5Zn0Z2kVdY6O2WULrFYLBaLxd5ur4mDZD14b8ogWS/dtxV+dmx9ysA2QUj9TQRWv5D7HyKwuIW9n0vc8tkpHP0W4BOg3wQ8wtlvA+PC1e8Ao8Ld7wFjQtHvAiNC2e8DdqHqKwCrUPc1gE1AfRVgEXBfB+gF0lcCWoH2tYBOYPpqQCNwfT3QF9i+AegJfN8CtAWhbwJagtS3AbIg9o2AJMh9M5C+SVGBvx6zAfmT0r+Bv8JMwP4kyFPir+cswF5KL3WLv14zAFBCLf56Tw9cparFX4upgaJUtPhrOS1QlY5W+vWTXrGgBFB/b72ev3/0igUdQPppP/nfowfKUUEFcP207y/yxKmgAYQ+PywoAFOfCH3A2MdCFzD3kdADBvq10AGG+pXQBgb7pdAEhvuF0AIc/VtoAK7+JciAs38KIuDugyAC/v4hiMCE/i7IwLRBsh68N2WQjMVisVgs9i5bln8LGScNcCrONQAAAABJRU5ErkJggg==";
// Get the current body of the message or appointment.
mailItem.body.getAsync(Office.CoercionType.Html, (bodyResult) => {
if (bodyResult.status === Office.AsyncResultStatus.Succeeded) {
// Insert the Base64-encoded image to the beginning of the body.
const options = { isInline: true, asyncContext: bodyResult.value };
mailItem.addFileAttachmentFromBase64Async(base64String, "sample.png", options, (attachResult) => {
if (attachResult.status === Office.AsyncResultStatus.Succeeded) {
let body = attachResult.asyncContext;
body = body.replace("<p class=MsoNormal>", `<p class=MsoNormal><img src="cid:sample.png">`);
mailItem.body.setAsync(body, { coercionType: Office.CoercionType.Html }, (setResult) => {
if (setResult.status === Office.AsyncResultStatus.Succeeded) {
console.log("Inline Base64-encoded image added to the body.");
} else {
console.log(setResult.error.message);
}
});
} else {
console.log(attachResult.error.message);
}
});
} else {
console.log(bodyResult.error.message);
}
});
Methods
append |
Appends on send the specified content to the end of the item body, after any signature. To use |
append |
Appends on send the specified content to the end of the item body, after any signature. To use |
get |
Returns the current body in a specified format. This method returns the entire current body in the format specified by |
get |
Returns the current body in a specified format. This method returns the entire current body in the format specified by |
get |
Gets a value that indicates whether the content is in HTML or text format. |
get |
Gets a value that indicates whether the content is in HTML or text format. |
prepend |
Adds the specified content to the beginning of the item body. |
prepend |
Adds the specified content to the beginning of the item body. |
prepend |
Prepends HTML or plain text to the beginning of a message or appointment body when the mail item is sent. To use |
prepend |
Prepends HTML or plain text to the beginning of a message or appointment body when the mail item is sent. To use |
set |
Replaces the entire body with the specified text. |
set |
Replaces the entire body with the specified text. |
set |
Replaces the selection in the body with the specified text. The |
set |
Replaces the selection in the body with the specified text. The |
set |
Adds a signature to the item body if it doesn't have an existing signature. If there's already a signature in the body, replaces that signature. |
set |
Adds a signature to the item body if it doesn't have an existing signature. If there's already a signature in the body, replaces that signature. |
Method Details
appendOnSendAsync(data, options, callback)
Appends on send the specified content to the end of the item body, after any signature.
To use appendOnSendAsync
, you must specify a supplementary permission in the manifest. Details vary with the type of manifest. See Understanding Outlook add-in permissions. To learn more about append-on-send and its configuration, see Implement append-on-send in your Outlook add-in.
appendOnSendAsync(data: string, options: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- data
-
string
The string to be added to the end of the body. The string is limited to 5,000 characters.
An object literal that contains one or more of the following properties:- asyncContext
: Developers can provide any object they wish to access in the callback function. coercionType
: The desired format for the data to be appended. The string in the data
parameter will be converted to this format.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. Any errors encountered will be provided in the asyncResult.error
property.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Compose
Recommended: Call getTypeAsync
, then pass its returned value to the options.coercionType
parameter.
Important:
If the user is running add-ins that implement the on-send feature using
ItemSend
in the manifest, append-on-send runs before on-send functionality.If your add-in implements the on-send feature and calls
appendOnSendAsync
in theItemSend
handler, theappendOnSendAsync
call returns an error as this scenario isn't supported.To clear data from a previous
appendOnSendAsync
call, you can call it again with thedata
parameter set tonull
.SVG files aren't supported. Use JPG or PNG files instead.
The
appendOnSendAsync
method doesn't support inline CSS. Use internal or external CSS instead.
Errors:
DataExceedsMaximumSize
: Thedata
parameter is longer than 5,000 characters.InvalidFormatError
: Theoptions.coercionType
parameter is set toOffice.CoercionType.Html
but the message body is in plain text.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/20-item-body/append-text-on-send.yaml
// This snippet appends text to the end of the message or appointment's body once it's sent.
const text = $("#text-field").val();
// It's recommended to call getTypeAsync and pass its returned value to the options.coercionType parameter of the appendOnSendAsync call.
Office.context.mailbox.item.body.getTypeAsync((asyncResult) => {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log("Action failed with error: " + asyncResult.error.message);
return;
}
const bodyFormat = asyncResult.value;
Office.context.mailbox.item.body.appendOnSendAsync(text, { coercionType: bodyFormat }, (asyncResult) => {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log("Action failed with error: " + asyncResult.error.message);
return;
}
console.log(`"${text}" will be appended to the body once the message or appointment is sent. Send the mail item to test this feature.`);
});
});
appendOnSendAsync(data, callback)
Appends on send the specified content to the end of the item body, after any signature.
To use appendOnSendAsync
, you must specify a supplementary permission in the manifest. Details vary with the type of manifest. See Understanding Outlook add-in permissions. To learn more about append-on-send and its configuration, see Implement append-on-send in your Outlook add-in.
appendOnSendAsync(data: string, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- data
-
string
The string to be added to the end of the body. The string is limited to 5,000 characters.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. Any errors encountered will be provided in the asyncResult.error
property.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Compose
Recommended: Call getTypeAsync
, then pass its returned value to the options.coercionType
parameter.
Important:
If the user is running add-ins that implement the on-send feature using
ItemSend
in the manifest, append-on-send runs before on-send functionality.If your add-in implements the on-send feature and calls
appendOnSendAsync
in theItemSend
handler, theappendOnSendAsync
call returns an error as this scenario isn't supported.To clear data from a previous
appendOnSendAsync
call, you can call it again with thedata
parameter set tonull
.SVG files aren't supported. Use JPG or PNG files instead.
The
appendOnSendAsync
method doesn't support inline CSS. Use internal or external CSS instead.
Errors:
DataExceedsMaximumSize
: Thedata
parameter is longer than 5,000 characters.InvalidFormatError
: Theoptions.coercionType
parameter is set toOffice.CoercionType.Html
but the message body is in plain text.
getAsync(coercionType, options, callback)
Returns the current body in a specified format.
This method returns the entire current body in the format specified by coercionType
.
getAsync(coercionType: Office.CoercionType | string, options: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult<string>) => void): void;
Parameters
- coercionType
-
Office.CoercionType | string
The format for the returned body.
- options
- Office.AsyncContextOptions
An object literal that contains one or more of the following properties:- asyncContext
: Developers can provide any object they wish to access in the callback function.
- callback
-
(asyncResult: Office.AsyncResult<string>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult. The body is provided in the requested format in the asyncResult.value
property.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Compose or Read
Important:
When working with HTML-formatted bodies, it's important to note that the value returned by the
Body.getAsync
method won't necessarily be the exact same value that was previously passed in theBody.setAsync
method. The client may modify the value passed tosetAsync
to make it render efficiently with its rendering engine.In Outlook on the web and new Outlook on Windows, if the body contains formatted elements, such as tables, lists, and links, specify
Office.CoercionType.Html
in thegetAsync
call. Otherwise, you may receive an unexpected value, such as an empty string.
Examples
// This example gets the body of the item as plain text.
Office.context.mailbox.item.body.getAsync(
"text",
{ asyncContext: "This is passed to the callback" },
function callback(result) {
// Do something with the result.
});
// The following is an example of the result parameter passed to the callback function.
{
"value": "TEXT of whole body (including threads below)",
"status": "succeeded",
"asyncContext": "This is passed to the callback"
}
getAsync(coercionType, callback)
Returns the current body in a specified format.
This method returns the entire current body in the format specified by coercionType
.
getAsync(coercionType: Office.CoercionType | string, callback?: (asyncResult: Office.AsyncResult<string>) => void): void;
Parameters
- coercionType
-
Office.CoercionType | string
The format for the returned body.
- callback
-
(asyncResult: Office.AsyncResult<string>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult. The body is provided in the requested format in the asyncResult.value
property.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Compose or Read
Important:
When working with HTML-formatted bodies, it's important to note that the value returned by the
Body.getAsync
method won't necessarily be the exact same value that was previously passed in theBody.setAsync
method. The client may modify the value passed tosetAsync
to make it render efficiently with its rendering engine.In Outlook on the web and new Outlook on Windows, if the body contains formatted elements, such as tables, lists, and links, specify
Office.CoercionType.Html
in thegetAsync
call. Otherwise, you may receive an unexpected value, such as an empty string.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/20-item-body/add-inline-base64-image.yaml
const mailItem = Office.context.mailbox.item;
const base64String =
"iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAnUExURQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN0S+bUAAAAMdFJOUwAQIDBAUI+fr7/P7yEupu8AAAAJcEhZcwAADsMAAA7DAcdvqGQAAAF8SURBVGhD7dfLdoMwDEVR6Cspzf9/b20QYOthS5Zn0Z2kVdY6O2WULrFYLBaLxd5ur4mDZD14b8ogWS/dtxV+dmx9ysA2QUj9TQRWv5D7HyKwuIW9n0vc8tkpHP0W4BOg3wQ8wtlvA+PC1e8Ao8Ld7wFjQtHvAiNC2e8DdqHqKwCrUPc1gE1AfRVgEXBfB+gF0lcCWoH2tYBOYPpqQCNwfT3QF9i+AegJfN8CtAWhbwJagtS3AbIg9o2AJMh9M5C+SVGBvx6zAfmT0r+Bv8JMwP4kyFPir+cswF5KL3WLv14zAFBCLf56Tw9cparFX4upgaJUtPhrOS1QlY5W+vWTXrGgBFB/b72ev3/0igUdQPppP/nfowfKUUEFcP207y/yxKmgAYQ+PywoAFOfCH3A2MdCFzD3kdADBvq10AGG+pXQBgb7pdAEhvuF0AIc/VtoAK7+JciAs38KIuDugyAC/v4hiMCE/i7IwLRBsh68N2WQjMVisVgs9i5bln8LGScNcCrONQAAAABJRU5ErkJggg==";
// Get the current body of the message or appointment.
mailItem.body.getAsync(Office.CoercionType.Html, (bodyResult) => {
if (bodyResult.status === Office.AsyncResultStatus.Succeeded) {
// Insert the Base64-encoded image to the beginning of the body.
const options = { isInline: true, asyncContext: bodyResult.value };
mailItem.addFileAttachmentFromBase64Async(base64String, "sample.png", options, (attachResult) => {
if (attachResult.status === Office.AsyncResultStatus.Succeeded) {
let body = attachResult.asyncContext;
body = body.replace("<p class=MsoNormal>", `<p class=MsoNormal><img src="cid:sample.png">`);
mailItem.body.setAsync(body, { coercionType: Office.CoercionType.Html }, (setResult) => {
if (setResult.status === Office.AsyncResultStatus.Succeeded) {
console.log("Inline Base64-encoded image added to the body.");
} else {
console.log(setResult.error.message);
}
});
} else {
console.log(attachResult.error.message);
}
});
} else {
console.log(bodyResult.error.message);
}
});
getTypeAsync(options, callback)
Gets a value that indicates whether the content is in HTML or text format.
getTypeAsync(options: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult<Office.CoercionType>) => void): void;
Parameters
- options
- Office.AsyncContextOptions
An object literal that contains one or more of the following properties:- asyncContext
: Developers can provide any object they wish to access in the callback function.
- callback
-
(asyncResult: Office.AsyncResult<Office.CoercionType>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. The content type is returned as one of the CoercionType
values in the asyncResult.value
property.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Compose
Important: In Outlook on Android and on iOS, this method isn't supported in the Message Compose mode. Only the Appointment Organizer mode is supported. For more information on supported APIs in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/20-item-body/get-body-format.yaml
// Get the mail item's body format (plain text or HTML) and log it to the console.
Office.context.mailbox.item.body.getTypeAsync((asyncResult) => {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log("Action failed with error: " + asyncResult.error.message);
return;
}
console.log("Body format: " + asyncResult.value);
});
getTypeAsync(callback)
Gets a value that indicates whether the content is in HTML or text format.
getTypeAsync(callback?: (asyncResult: Office.AsyncResult<Office.CoercionType>) => void): void;
Parameters
- callback
-
(asyncResult: Office.AsyncResult<Office.CoercionType>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. The content type is returned as one of the CoercionType
values in the asyncResult.value
property.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Compose
Important: In Outlook on Android and on iOS, this method isn't supported in the Message Compose mode. Only the Appointment Organizer mode is supported. For more information on supported APIs in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
prependAsync(data, options, callback)
Adds the specified content to the beginning of the item body.
prependAsync(data: string, options: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- data
-
string
The string to be inserted at the beginning of the body. The string is limited to 1,000,000 characters.
An object literal that contains one or more of the following properties:- asyncContext
: Developers can provide any object they wish to access in the callback function. coercionType
: The desired format for the body. The string in the data
parameter will be converted to this format.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. Any errors encountered will be provided in the asyncResult.error
property.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Compose
Recommended: Call getTypeAsync
, then pass the returned value to the options.coercionType
parameter.
Important:
After the content is prepended, the position of the cursor depends on which client the add-in is running. In Outlook on the web and on Windows (new and classic), the cursor position remains the same in the preexisting content of the body. For example, if the cursor was positioned at the beginning of the body prior to the
prependAsync
call, it will appear between the prepended content and the preexisting content of the body after the call. In Outlook on Mac, the cursor position isn't preserved. The cursor disappears after theprependAsync
call and only reappears when the user selects something in the body of the mail item.When working with HTML-formatted bodies, it's important to note that the client may modify the value passed to
prependAsync
to make it render efficiently with its rendering engine. This means that the value returned from a subsequent call to theBody.getAsync
method (introduced in Mailbox 1.3) won't necessarily contain the exact value that was passed in the previousprependAsync
call.When including links in HTML markup, you can disable online link preview by setting the
id
attribute on the anchor (<a>) to "LPNoLP" (see the Examples section for a sample).In Outlook on Android and on iOS, this method isn't supported in the Message Compose mode. Only the Appointment Organizer mode is supported. For more information on supported APIs in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
SVG files aren't supported. Use JPG or PNG files instead.
The
prependAsync
method doesn't support inline CSS. Use internal or external CSS instead.
Errors:
DataExceedsMaximumSize
: The data parameter is longer than 1,000,000 characters.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/20-item-body/prepend-text-to-item-body.yaml
/* This snippet adds text to the beginning of the message or appointment's body.
When prepending a link in HTML markup to the body, you can disable the online link preview by setting the anchor tag's id attribute to "LPNoLP". For example, '<a id="LPNoLP" href="https://www.contoso.com">Click here!</a>'.
*/
const text = $("#text-field").val().toString();
// It's recommended to call getTypeAsync and pass its returned value to the options.coercionType parameter of the prependAsync call.
Office.context.mailbox.item.body.getTypeAsync((asyncResult) => {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log("Action failed with error: " + asyncResult.error.message);
return;
}
const bodyFormat = asyncResult.value;
Office.context.mailbox.item.body.prependAsync(text, { coercionType: bodyFormat }, (asyncResult) => {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log("Action failed with error: " + asyncResult.error.message);
return;
}
console.log(`"${text}" prepended to the body.`);
});
});
prependAsync(data, callback)
Adds the specified content to the beginning of the item body.
prependAsync(data: string, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- data
-
string
The string to be inserted at the beginning of the body. The string is limited to 1,000,000 characters.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. Any errors encountered will be provided in the asyncResult.error
property.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Compose
Recommended: Call getTypeAsync
, then pass the returned value to the options.coercionType
parameter.
Important:
After the content is prepended, the position of the cursor depends on which client the add-in is running. In Outlook on the web and on Windows (new and classic), the cursor position remains the same in the preexisting content of the body. For example, if the cursor was positioned at the beginning of the body prior to the
prependAsync
call, it will appear between the prepended content and the preexisting content of the body after the call. In Outlook on Mac, the cursor position isn't preserved. The cursor disappears after theprependAsync
call and only reappears when the user selects something in the body of the mail item.When working with HTML-formatted bodies, it's important to note that the client may modify the value passed to
prependAsync
to make it render efficiently with its rendering engine. This means that the value returned from a subsequent call to theBody.getAsync
method (introduced in Mailbox 1.3) won't necessarily contain the exact value that was passed in the previousprependAsync
call.When including links in HTML markup, you can disable online link preview by setting the
id
attribute on the anchor (<a>) to "LPNoLP" (see the Examples section for a sample).In Outlook on Android and on iOS, this method isn't supported in the Message Compose mode. Only the Appointment Organizer mode is supported. For more information on supported APIs in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
SVG files aren't supported. Use JPG or PNG files instead.
The
prependAsync
method doesn't support inline CSS. Use internal or external CSS instead.
Errors:
DataExceedsMaximumSize
: The data parameter is longer than 1,000,000 characters.
prependOnSendAsync(data, options, callback)
Prepends HTML or plain text to the beginning of a message or appointment body when the mail item is sent.
To use prependOnSendAsync
, you must specify a supplementary permission in the manifest. Details vary with the type of manifest. For guidance, see Understanding Outlook add-in permissions.
prependOnSendAsync(data: string, options: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- data
-
string
The string to be prepended to the beginning of the message or appointment body. The string is limited to 5,000 characters.
An object literal that contains one or more of the following properties:- asyncContext
: Any object that can be accessed in the callback function. coercionType
: The desired format for the body. The string in the data
parameter is converted to this format.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. Any errors encountered will be provided in the asyncResult.error
property.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Compose
Recommended: Call getTypeAsync
, then pass its returned value to the options.coercionType
parameter.
Important: When implementing prependOnSendAsync
, keep the following in mind.
In a Smart Alerts add-in, the prepend-on-send feature runs first.
A new line is added after the prepended content.
If multiple active add-ins call
prependOnSendAsync
, the order of the inserted content depends on the order in which the add-in runs. The content of the last run add-in appears above previously prepended content.If the add-in attempts to insert HTML into a plain text body, the content won't be prepended. Conversely, plain text will be inserted into an HTML body.
SVG files aren't supported. Use JPG or PNG files instead.
The
prependOnSendAsync
method doesn't support inline CSS. Use internal or external CSS instead.
Errors:
DataExceedsMaximumSize
: Thedata
parameter exceeds 5,000 characters.InvalidFormatError
: Theoptions.coercionType
parameter is set toOffice.CoercionType.Html
, but the item body is in plain text format.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/20-item-body/prepend-text-on-send.yaml
// This snippet prepends text to the beginning of the message or appointment's body once it's sent.
const text = $("#text-field").val().toString();
// It's recommended to call getTypeAsync and pass its returned value to the options.coercionType parameter of the prependOnSendAsync call.
Office.context.mailbox.item.body.getTypeAsync((asyncResult) => {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log("Action failed with error: " + asyncResult.error.message);
return;
}
const bodyFormat = asyncResult.value;
Office.context.mailbox.item.body.prependOnSendAsync(text, { coercionType: bodyFormat }, (asyncResult) => {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log("Action failed with error: " + asyncResult.error.message);
return;
}
console.log(`"${text}" will be prepended to the body once the message or appointment is sent. Send the mail item to test this feature.`);
});
});
prependOnSendAsync(data, callback)
Prepends HTML or plain text to the beginning of a message or appointment body when the mail item is sent.
To use prependOnSendAsync
, you must specify a supplementary permission in the manifest. Details vary with the type of manifest. For guidance, see Understanding Outlook add-in permissions.
prependOnSendAsync(data: string, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- data
-
string
The string to be prepended to the beginning of the message or appointment body. The string is limited to 5,000 characters.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. Any errors encountered will be provided in the asyncResult.error
property.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Compose
Recommended: Call getTypeAsync
, then pass its returned value to the options.coercionType
parameter.
Important: When implementing prependOnSendAsync
, keep the following in mind.
In a Smart Alerts add-in, the prepend-on-send feature runs first.
A new line is added after the prepended content.
If multiple active add-ins call
prependOnSendAsync
, the order of the inserted content depends on the order in which the add-in runs. The content of the last run add-in appears above previously prepended content.If the add-in attempts to insert HTML into a plain text body, the content won't be prepended. Conversely, plain text will be inserted into an HTML body.
SVG files aren't supported. Use JPG or PNG files instead.
The
prependOnSendAsync
method doesn't support inline CSS. Use internal or external CSS instead.
Errors:
DataExceedsMaximumSize
: Thedata
parameter exceeds 5,000 characters.InvalidFormatError
: Theoptions.coercionType
parameter is set toOffice.CoercionType.Html
, but the item body is in plain text format.
setAsync(data, options, callback)
Replaces the entire body with the specified text.
setAsync(data: string, options: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- data
-
string
The string that will replace the existing body. The string is limited to 1,000,000 characters.
An object literal that contains one or more of the following properties:- asyncContext
: Developers can provide any object they wish to access in the callback function. coercionType
: The desired format for the body. The string in the data
parameter will be converted to this format.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult. Any errors encountered will be provided in the asyncResult.error
property.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Compose
Recommended: Call getTypeAsync
, then pass the returned value to the options.coercionType
parameter.
Important:
After the body is replaced with the specified content, the position of the cursor depends on which client the add-in is running. In classic Outlook on Windows, the cursor appears at the beginning of the body of the mail item. In Outlook on the web and new Outlook on Windows, the cursor appears at the end of the body of the mail item. In Outlook on Mac, the cursor position isn't preserved. The cursor disappears after the
prependAsync
call and only reappears when the user selects something in the body of the mail item.When working with HTML-formatted bodies, it's important to note that the value returned by the
Body.getAsync
method won't necessarily be the exact same value that was previously passed in theBody.setAsync
method. The client may modify the value passed tosetAsync
to make it render efficiently with its rendering engine.When including links in HTML markup, you can disable online link preview by setting the
id
attribute on the anchor (<a>) to "LPNoLP" (see the Examples section for a sample).In Outlook on Windows (classic) and on Mac, the add-in user isn't able to revert this action with the Undo command.
In Outlook on Android and on iOS, this method isn't supported in the Message Compose mode. Only the Appointment Organizer mode is supported. For more information on supported APIs in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
SVG files aren't supported. Use JPG or PNG files instead.
The
setAsync
method doesn't support inline CSS. Use internal or external CSS instead.
Errors:
DataExceedsMaximumSize
: The data parameter is longer than 1,000,000 characters.InvalidFormatError
: Theoptions.coercionType
parameter is set toOffice.CoercionType.Html
and the message body is in plain text.
Examples
// When including links in HTML markup, you can disable online link preview
// by setting the id attribute on the anchor (<a>) to "LPNoLP".
Office.context.mailbox.item.body.setAsync(
'<a id="LPNoLP" href="http://www.contoso.com">Click here!</a>',
{
coercionType: Office.CoercionType.Html,
asyncContext: "This is passed to the callback"
},
(result) => {
// Process the result.
}
);
// The following is an example of the result parameter passed to the callback function.
{
"value": null,
"status": "succeeded",
"asyncContext": "This is passed to the callback"
}
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/20-item-body/add-inline-base64-image.yaml
const mailItem = Office.context.mailbox.item;
const base64String =
"iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAnUExURQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN0S+bUAAAAMdFJOUwAQIDBAUI+fr7/P7yEupu8AAAAJcEhZcwAADsMAAA7DAcdvqGQAAAF8SURBVGhD7dfLdoMwDEVR6Cspzf9/b20QYOthS5Zn0Z2kVdY6O2WULrFYLBaLxd5ur4mDZD14b8ogWS/dtxV+dmx9ysA2QUj9TQRWv5D7HyKwuIW9n0vc8tkpHP0W4BOg3wQ8wtlvA+PC1e8Ao8Ld7wFjQtHvAiNC2e8DdqHqKwCrUPc1gE1AfRVgEXBfB+gF0lcCWoH2tYBOYPpqQCNwfT3QF9i+AegJfN8CtAWhbwJagtS3AbIg9o2AJMh9M5C+SVGBvx6zAfmT0r+Bv8JMwP4kyFPir+cswF5KL3WLv14zAFBCLf56Tw9cparFX4upgaJUtPhrOS1QlY5W+vWTXrGgBFB/b72ev3/0igUdQPppP/nfowfKUUEFcP207y/yxKmgAYQ+PywoAFOfCH3A2MdCFzD3kdADBvq10AGG+pXQBgb7pdAEhvuF0AIc/VtoAK7+JciAs38KIuDugyAC/v4hiMCE/i7IwLRBsh68N2WQjMVisVgs9i5bln8LGScNcCrONQAAAABJRU5ErkJggg==";
// Get the current body of the message or appointment.
mailItem.body.getAsync(Office.CoercionType.Html, (bodyResult) => {
if (bodyResult.status === Office.AsyncResultStatus.Succeeded) {
// Insert the Base64-encoded image to the beginning of the body.
const options = { isInline: true, asyncContext: bodyResult.value };
mailItem.addFileAttachmentFromBase64Async(base64String, "sample.png", options, (attachResult) => {
if (attachResult.status === Office.AsyncResultStatus.Succeeded) {
let body = attachResult.asyncContext;
body = body.replace("<p class=MsoNormal>", `<p class=MsoNormal><img src="cid:sample.png">`);
mailItem.body.setAsync(body, { coercionType: Office.CoercionType.Html }, (setResult) => {
if (setResult.status === Office.AsyncResultStatus.Succeeded) {
console.log("Inline Base64-encoded image added to the body.");
} else {
console.log(setResult.error.message);
}
});
} else {
console.log(attachResult.error.message);
}
});
} else {
console.log(bodyResult.error.message);
}
});
setAsync(data, callback)
Replaces the entire body with the specified text.
setAsync(data: string, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- data
-
string
The string that will replace the existing body. The string is limited to 1,000,000 characters.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult. Any errors encountered will be provided in the asyncResult.error
property.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Compose
Recommended: Call getTypeAsync
, then pass the returned value to the options.coercionType
parameter.
Important:
After the body is replaced with the specified content, the position of the cursor depends on which client the add-in is running. In classic Outlook on Windows, the cursor appears at the beginning of the body of the mail item. In Outlook on the web and new Outlook on Windows, the cursor appears at the end of the body of the mail item. In Outlook on Mac, the cursor position isn't preserved. The cursor disappears after the
prependAsync
call and only reappears when the user selects something in the body of the mail item.When working with HTML-formatted bodies, it's important to note that the value returned by the
Body.getAsync
method won't necessarily be the exact same value that was previously passed in theBody.setAsync
method. The client may modify the value passed tosetAsync
to make it render efficiently with its rendering engine.When including links in HTML markup, you can disable online link preview by setting the
id
attribute on the anchor (<a>) to "LPNoLP" (see the Examples section for a sample).In Outlook on Windows (classic) and on Mac, the add-in user isn't able to revert this action with the Undo command.
In Outlook on Android and on iOS, this method isn't supported in the Message Compose mode. Only the Appointment Organizer mode is supported. For more information on supported APIs in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
SVG files aren't supported. Use JPG or PNG files instead.
The
setAsync
method doesn't support inline CSS. Use internal or external CSS instead.
Errors:
DataExceedsMaximumSize
: The data parameter is longer than 1,000,000 characters.InvalidFormatError
: Theoptions.coercionType
parameter is set toOffice.CoercionType.Html
and the message body is in plain text.
setSelectedDataAsync(data, options, callback)
Replaces the selection in the body with the specified text.
The setSelectedDataAsync
method inserts the specified string at the cursor location in the body of the item, or, if text is selected in the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content.
setSelectedDataAsync(data: string, options: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- data
-
string
The string that will replace the existing body. The string is limited to 1,000,000 characters.
An object literal that contains one or more of the following properties:- asyncContext
: Developers can provide any object they wish to access in the callback function. coercionType
: The desired format for the body. The string in the data
parameter will be converted to this format.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. Any errors encountered will be provided in the asyncResult.error
property.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Compose
Recommended: Call getTypeAsync
then pass the returned value to the options.coercionType
parameter.
*Important:
When including links in HTML markup, you can disable online link preview by setting the
id
attribute on the anchor (<a>) to "LPNoLP" (see the Examples section for a sample).SVG files aren't supported. Use JPG or PNG files instead.
The
setSelectedDataAsync
method doesn't support inline CSS. Use internal or external CSS instead.
Errors:
DataExceedsMaximumSize
: Thedata
parameter is longer than 1,000,000 characters.InvalidFormatError
: Theoptions.coercionType
parameter is set toOffice.CoercionType.Html
and the message body is in plain text.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/20-item-body/replace-selected-text.yaml
/* This snippet replaces selected text in a message or appointment's body with specified text.
If you want to use a link in HTML markup as a value of the setSelectedDataAsync call's data parameter, you can disable online link preview by setting the anchor tag's id attribute to "LPNoLP". For example, '<a id="LPNoLP" href="https://www.contoso.com">Click here!</a>'.
*/
const text = $("#text-field").val().toString();
// It's recommended to call getTypeAsync and pass its returned value to the options.coercionType parameter of the prependAsync call.
Office.context.mailbox.item.body.getTypeAsync((asyncResult) => {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log("Action failed with error: " + asyncResult.error.message);
return;
}
const bodyFormat = asyncResult.value;
Office.context.mailbox.item.body.setSelectedDataAsync(text, { coercionType: bodyFormat }, (asyncResult) => {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log("Action failed with error: " + asyncResult.error.message);
return;
}
console.log(`Replaced selected text with "${text}".`);
});
});
setSelectedDataAsync(data, callback)
Replaces the selection in the body with the specified text.
The setSelectedDataAsync
method inserts the specified string at the cursor location in the body of the item, or, if text is selected in the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content.
setSelectedDataAsync(data: string, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- data
-
string
The string that will replace the existing body. The string is limited to 1,000,000 characters.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. Any errors encountered will be provided in the asyncResult.error
property.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Compose
Recommended: Call getTypeAsync
then pass the returned value to the options.coercionType
parameter.
*Important:
When including links in HTML markup, you can disable online link preview by setting the
id
attribute on the anchor (<a>) to "LPNoLP" (see the Examples section for a sample).SVG files aren't supported. Use JPG or PNG files instead.
The
setSelectedDataAsync
method doesn't support inline CSS. Use internal or external CSS instead.
Errors:
DataExceedsMaximumSize
: Thedata
parameter is longer than 1,000,000 characters.InvalidFormatError
: Theoptions.coercionType
parameter is set toOffice.CoercionType.Html
and the message body is in plain text.
setSignatureAsync(data, options, callback)
Adds a signature to the item body if it doesn't have an existing signature. If there's already a signature in the body, replaces that signature.
setSignatureAsync(data: string, options: Office.AsyncContextOptions & CoercionTypeOptions, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- data
-
string
The string that represents the signature to be set in the body of the mail. This string is limited to 30,000 characters.
An object literal that contains one or more of the following properties:- asyncContext
: Developers can provide any object they wish to access in the callback function. coercionType
: The format the signature should be set to. If Text, the method sets the signature to plain text, removing any HTML tags present. If Html, the method sets the signature to HTML.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Compose
Important:
In Outlook on the web and new Outlook on Windows,
setSignatureAsync
only works on messages.This method is supported in Message Compose on Outlook on Android and on iOS starting in Version 4.2352.0. For a sample scenario, see Implement event-based activation in Outlook mobile add-ins. To learn more about APIs supported in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
The behavior of
setSignatureAsync
differs if you call it in the event handler of an add-in that implements the event-based activation feature using LaunchEvent in the manifest. When the user composes a new item (including reply or forward), the signature is set but doesn't modify the form. This means if the user closes the form without making other edits, they won't be prompted to save changes.SVG files aren't supported in mail signatures. Use JPG or PNG files instead.
The
setSignatureAsync
method doesn't support inline CSS. Use internal or external CSS instead.
Errors:
DataExceedsMaximumSize
: Thedata
parameter is longer than 30,000 characters.InvalidFormatError
: Theoptions.coercionType
parameter is set toOffice.CoercionType.Html
and the message body is in plain text.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/90-other-item-apis/work-with-client-signatures.yaml
// Set the signature for the current item with inline image.
const modIcon1Base64 = "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAYAAAByDd+UAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2ZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDpDRDMxMDg1MjBCNDZFMTExODE2MkM1RUI2M0M4MDYxRCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpFMTUxQjgyRjQ2MEQxMUUxODlFMkQwNTYzQ0YwMTUxMiIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpFMTUxQjgyRTQ2MEQxMUUxODlFMkQwNTYzQ0YwMTUxMiIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1LjEgV2luZG93cyI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkQxMzEwODUyMEI0NkUxMTE4MTYyQzVFQjYzQzgwNjFEIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkNEMzEwODUyMEI0NkUxMTE4MTYyQzVFQjYzQzgwNjFEIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+uC/WfAAAAehJREFUeNpilCzfwEAEkAbiECA2A2J1IOaHin8E4ptAfBaIVwLxU0IGMRKw0B6IW4DYhoE4cASIK6E0VsCEQ1wUiNcB8QESLGOAqj0MxBuhZhBloS4QnwHiQAbygR/UDF1CFupCXSjHQDmQg5qli8tCUBBsQUoQ1AD8UDNFsVk4n0o+w+bT+egWglKjNymmeGhLkqLcG2oHAwtUoIuQDj5OVgZPLUmwRe5aEmAxqYqNpFgKssOcCeplM0KqdST5GfpDDRm0JfkYrj3/SE7QguyQY4ImYYLgCtAS10kHGMw6dzNsv/qC7OwCClJXYlR++v6b4er3j5QmIFcmaNlIL6AOslCIjhYKMTHQGTBBqxh6gXcgC6/R0cKbIAv30dHCfaAKGJTxHxJSqS3Fz9DkowNmywpyMcgA8fF7b8D8VWcfM6w8+4gYC+VB+RCk8hSh0gaUD4/dewvlvUWRe/z+GzGWgex4BGtiOAHxXhoHpzMoSGHZAhSPW2lo2VZYWkHOh4nEtLrIAE+hZmNUwK+B2BOIv1PRsu9QM1/jatNcBtVZ0IREKXgENesyoVYbzNIdFFi2A5tl+NqlL6BB4QBNzsSCU1A9nlAzMAALAQMOQl0qB23qWwKxIlIrDBQ394H4OBCvISYqAAIMACVibHDqsO7zAAAAAElFTkSuQmCC";
Office.context.mailbox.item.addFileAttachmentFromBase64Async(
modIcon1Base64,
"myImage.png",
{ isInline: true },
function(result) {
if (result.status == Office.AsyncResultStatus.Succeeded) {
const signature = $("#signature").val() + "<img src='cid:myImage.png'>";
console.log(`Setting signature to "${signature}".`);
Office.context.mailbox.item.body.setSignatureAsync(
signature,
{ coercionType: "html" },
function(asyncResult) {
console.log(`setSignatureAsync: ${asyncResult.status}`);
}
);
} else {
console.error(`addFileAttachmentFromBase64Async: ${result.error}`);
}
}
);
...
// Set the signature for the current item.
const signature = $("#signature").val();
console.log(`Setting signature to "${signature}".`);
Office.context.mailbox.item.body.setSignatureAsync(signature, function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
console.log("setSignatureAsync succeeded");
} else {
console.error(asyncResult.error);
}
});
setSignatureAsync(data, callback)
Adds a signature to the item body if it doesn't have an existing signature. If there's already a signature in the body, replaces that signature.
setSignatureAsync(data: string, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- data
-
string
The string that represents the signature to be set in the body of the mail. This string is limited to 30,000 characters.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Compose
Important:
In Outlook on the web and new Outlook on Windows,
setSignatureAsync
only works on messages.This method is supported in Message Compose on Outlook on Android and on iOS starting in Version 4.2352.0. For a sample scenario, see Implement event-based activation in Outlook mobile add-ins. To learn more about APIs supported in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
The behavior of
setSignatureAsync
differs if you call it in the event handler of an add-in that implements the event-based activation feature using LaunchEvent in the manifest. When the user composes a new item (including reply or forward), the signature is set but doesn't modify the form. This means if the user closes the form without making other edits, they won't be prompted to save changes.SVG files aren't supported in mail signatures. Use JPG or PNG files instead.
The
setSignatureAsync
method doesn't support inline CSS. Use internal or external CSS instead.
Errors:
DataExceedsMaximumSize
: Thedata
parameter is longer than 30,000 characters.InvalidFormatError
: Theoptions.coercionType
parameter is set toOffice.CoercionType.Html
and the message body is in plain text.
Office Add-ins