Office.MessageCompose interface
The message compose mode of Office.context.mailbox.item.
Important:
This is an internal Outlook object, not directly exposed through existing interfaces. You should treat this as a mode of
Office.context.mailbox.item
. For more information, refer to the Object Model page.When calling
Office.context.mailbox.item
on a message, note that the Reading Pane in the Outlook client must be turned on. For guidance on how to configure the Reading Pane, see Use and configure the Reading Pane to preview messages.
Parent interfaces:
- Extends
Properties
bcc | Gets an object that provides methods to get or update the recipients on the Bcc (blind carbon copy) line of a message. Depending on the client/platform (i.e., Windows, Mac, etc.), limits may apply on how many recipients you can get or update. See the Recipients object for more details. |
body | Gets an object that provides methods for manipulating the body of an item. |
categories | Gets an object that provides methods for managing the item's categories. |
cc | Provides access to the Cc (carbon copy) recipients of a message. The type of object and level of access depend on the mode of the current item. The |
conversation |
Gets an identifier for the email conversation that contains a particular message. You can get an integer for this property if your mail app is activated in read forms or responses in compose forms. If subsequently the user changes the subject of the reply message, upon sending the reply, the conversation ID for that message will change and that value you obtained earlier will no longer apply. You get null for this property for a new item in a compose form. If the user sets a subject and saves the item, the |
from | Gets the email address of the sender of a message. The |
internet |
Gets or sets the custom internet headers of a message. The To learn more, see Get and set internet headers on a message in an Outlook add-in. |
item |
Gets the type of item that an instance represents. The |
notification |
Gets the notification messages for an item. |
series |
Gets the ID of the series that an instance belongs to. In Outlook on the web, on Windows (new and classic), and on Mac, the |
subject | Gets or sets the description that appears in the subject field of an item. The The |
to | Provides access to the recipients on the To line of a message. The type of object and level of access depend on the mode of the current item. The |
Methods
add |
Adds a file to a message or appointment as an attachment. The |
add |
Adds a file to a message or appointment as an attachment. The |
add |
Adds a file to a message or appointment as an attachment. The You can subsequently use the identifier with the |
add |
Adds a file to a message or appointment as an attachment. The You can subsequently use the identifier with the |
add |
Adds an event handler for a supported event. Note: Events are only available with task pane implementation. For supported events, refer to the Item object model events section. |
add |
Adds an event handler for a supported event. Note: Events are only available with task pane implementation. For supported events, refer to the Item object model events section. |
add |
Adds an Exchange item, such as a message, as an attachment to the message or appointment. The You can subsequently use the identifier with the If your Office Add-in is running in Outlook on the web or new Outlook on Windows, the |
add |
Adds an Exchange item, such as a message, as an attachment to the message or appointment. The You can subsequently use the identifier with the If your Office Add-in is running in Outlook on the web or new Outlook on Windows, the |
close() | Closes the current item that is being composed. The behavior of the In Outlook on Windows (classic) and on Mac, the |
disable |
Disables the Outlook client signature. The behavior of this method depends on which client the add-in is running.
|
disable |
Disables the Outlook client signature. The behavior of this method depends on which client the add-in is running.
|
get |
Gets an attachment from a message or appointment and returns it as an The |
get |
Gets an attachment from a message or appointment and returns it as an The |
get |
Gets the item's attachments as an array. |
get |
Gets the item's attachments as an array. |
get |
Specifies the type of message compose and its coercion type. The message can be new, or a reply or forward. The coercion type can be HTML or plain text. |
get |
Specifies the type of message compose and its coercion type. The message can be new, or a reply or forward. The coercion type can be HTML or plain text. |
get |
Gets initialization data passed when the add-in is activated by an actionable message. |
get |
Gets initialization data passed when the add-in is activated by an actionable message. |
get |
Asynchronously gets the Exchange Web Services (EWS) item identifier of a saved item. When invoked, this method returns the item ID via the callback function. |
get |
Asynchronously gets the Exchange Web Services (EWS) item identifier of a saved item. When invoked, this method returns the item ID via the callback function. |
get |
Asynchronously returns selected data from the subject or body of a message. If there is no selection but the cursor is in the body or subject, the method returns an empty string for the selected data. If a field other than the body or subject is selected, the method returns the To access the selected data from the callback function, call |
get |
Asynchronously returns selected data from the subject or body of a message. If there is no selection but the cursor is in the body or subject, the method returns an empty string for the selected data. If a field other than the body or subject is selected, the method returns the To access the selected data from the callback function, call |
get |
Gets the properties of an appointment or message in a shared folder or shared mailbox. For more information around using this API, see Enable shared folders and shared mailbox scenarios in an Outlook add-in. |
get |
Gets the properties of an appointment or message in a shared folder or shared mailbox. For more information around using this API, see Enable shared folders and shared mailbox scenarios in an Outlook add-in. |
is |
Gets if the client signature is enabled. In Outlook on Windows (classic) and on Mac, the API call returns |
is |
Gets if the client signature is enabled. In Outlook on Windows (classic) and on Mac, the API call returns |
load |
Asynchronously loads custom properties for this add-in on the selected item. Custom properties are stored as key-value pairs on a per-app, per-item basis. This method returns a CustomProperties object in the callback, which provides methods to access the custom properties specific to the current item and the current add-in. Custom properties aren't encrypted on the item, so this shouldn't be used as secure storage. The custom properties are provided as a |
remove |
Removes an attachment from a message or appointment. The |
remove |
Removes an attachment from a message or appointment. The |
remove |
Removes the event handlers for a supported event type. Note: Events are only available with task pane implementation. For supported events, refer to the Item object model events section. |
remove |
Removes the event handlers for a supported event type. Note: Events are only available with task pane implementation. For supported events, refer to the Item object model events section. |
save |
Asynchronously saves the current message as a draft. |
save |
Asynchronously saves the current message as a draft. |
set |
Asynchronously inserts data into the body or subject of a message. The |
set |
Asynchronously inserts data into the body or subject of a message. The |
Property Details
bcc
Gets an object that provides methods to get or update the recipients on the Bcc (blind carbon copy) line of a message.
Depending on the client/platform (i.e., Windows, Mac, etc.), limits may apply on how many recipients you can get or update. See the Recipients object for more details.
bcc: Recipients;
Property Value
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
Office.context.mailbox.item.bcc.setAsync( ['alice@contoso.com', 'bob@contoso.com'] );
Office.context.mailbox.item.bcc.addAsync( ['jason@contoso.com'] );
Office.context.mailbox.item.bcc.getAsync(callback);
function callback(asyncResult) {
const arrayOfBccRecipients = asyncResult.value;
}
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/30-recipients-and-attendees/get-set-bcc-message-compose.yaml
Office.context.mailbox.item.bcc.getAsync(function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
const msgBcc = asyncResult.value;
console.log("Message being blind-copied to:");
for (let i = 0; i < msgBcc.length; i++) {
console.log(msgBcc[i].displayName + " (" + msgBcc[i].emailAddress + ")");
}
} else {
console.error(asyncResult.error);
}
});
...
const email = $("#emailBcc")
.val()
.toString();
const emailArray = [email];
Office.context.mailbox.item.bcc.setAsync(emailArray, function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
console.log("Succeeded in setting Bcc field.");
} else {
console.error(asyncResult.error);
}
});
body
Gets an object that provides methods for manipulating the body of an item.
body: Body;
Property Value
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
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"
}
categories
Gets an object that provides methods for managing the item's categories.
categories: Categories;
Property Value
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Important: In Outlook on the web and new Outlook on Windows, you can't use the API to manage categories on a message in Compose mode.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/45-categories/work-with-categories.yaml
Office.context.mailbox.item.categories.getAsync(function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
const categories = asyncResult.value;
if (categories && categories.length > 0) {
console.log("Categories assigned to this item:");
console.log(JSON.stringify(categories));
} else {
console.log("There are no categories assigned to this item.");
}
} else {
console.error(asyncResult.error);
}
});
...
// Note: In order for you to successfully add a category,
// it must be in the mailbox categories master list.
Office.context.mailbox.masterCategories.getAsync(function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
const masterCategories = asyncResult.value;
if (masterCategories && masterCategories.length > 0) {
// Grab the first category from the master list.
const categoryToAdd = [masterCategories[0].displayName];
Office.context.mailbox.item.categories.addAsync(categoryToAdd, function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
console.log(`Successfully assigned category '${categoryToAdd}' to item.`);
} else {
console.log("categories.addAsync call failed with error: " + asyncResult.error.message);
}
});
} else {
console.log("There are no categories in the master list on this mailbox. You can add categories using Office.context.mailbox.masterCategories.addAsync.");
}
} else {
console.error(asyncResult.error);
}
});
...
Office.context.mailbox.item.categories.getAsync(function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
const categories = asyncResult.value;
if (categories && categories.length > 0) {
// Grab the first category assigned to this item.
const categoryToRemove = [categories[0].displayName];
Office.context.mailbox.item.categories.removeAsync(categoryToRemove, function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
console.log(`Successfully unassigned category '${categoryToRemove}' from this item.`);
} else {
console.log("categories.removeAsync call failed with error: " + asyncResult.error.message);
}
});
} else {
console.log("There are no categories assigned to this item.");
}
} else {
console.error(asyncResult.error);
}
});
cc
Provides access to the Cc (carbon copy) recipients of a message. The type of object and level of access depend on the mode of the current item.
The cc
property returns a Recipients
object that provides methods to get or update the recipients on the Cc line of the message. However, depending on the client/platform (i.e., Windows, Mac, etc.), limits may apply on how many recipients you can get or update. See the Recipients object for more details.
cc: Recipients;
Property Value
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
Office.context.mailbox.item.cc.setAsync( ['alice@contoso.com', 'bob@contoso.com'] );
Office.context.mailbox.item.cc.addAsync( ['jason@contoso.com'] );
Office.context.mailbox.item.cc.getAsync(callback);
function callback(asyncResult) {
const arrayOfCcRecipients = asyncResult.value;
}
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/30-recipients-and-attendees/get-set-cc-message-compose.yaml
Office.context.mailbox.item.cc.getAsync(function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
const msgCc = asyncResult.value;
console.log("Message being copied to:");
for (let i = 0; i < msgCc.length; i++) {
console.log(msgCc[i].displayName + " (" + msgCc[i].emailAddress + ")");
}
} else {
console.error(asyncResult.error);
}
});
...
const email = $("#emailCc")
.val()
.toString();
const emailArray = [email];
Office.context.mailbox.item.cc.setAsync(emailArray, function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
console.log("Succeeded in setting Cc field.");
} else {
console.error(asyncResult.error);
}
});
conversationId
Gets an identifier for the email conversation that contains a particular message.
You can get an integer for this property if your mail app is activated in read forms or responses in compose forms. If subsequently the user changes the subject of the reply message, upon sending the reply, the conversation ID for that message will change and that value you obtained earlier will no longer apply.
You get null for this property for a new item in a compose form. If the user sets a subject and saves the item, the conversationId
property will return a value.
conversationId: string;
Property Value
string
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/90-other-item-apis/get-conversation-id-message.yaml
console.log(`Conversation ID: ${Office.context.mailbox.item.conversationId}`);
from
Gets the email address of the sender of a message.
The from
property returns a From
object that provides a method to get the from value.
from: From;
Property Value
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Important: This property is supported in Outlook on Android and on iOS. For a sample scenario, see Implement event-based activation in Outlook mobile add-ins.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/30-recipients-and-attendees/get-from-message-compose.yaml
Office.context.mailbox.item.from.getAsync(function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
const msgFrom = asyncResult.value;
console.log("Message from: " + msgFrom.displayName + " (" + msgFrom.emailAddress + ")");
} else {
console.error(asyncResult.error);
}
});
internetHeaders
Gets or sets the custom internet headers of a message.
The internetHeaders
property returns an InternetHeaders
object that provides methods to manage the internet headers on the message.
To learn more, see Get and set internet headers on a message in an Outlook add-in.
internetHeaders: InternetHeaders;
Property Value
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Important: The internet headers API is supported in Outlook on Android and on iOS starting in Version 4.2405.0. To learn more about features supported in Outlook on mobile devices, 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/70-mime-headers/manage-custom-internet-headers-message-compose.yaml
Office.context.mailbox.item.internetHeaders.getAsync(
["preferred-fruit", "preferred-vegetable", "best-vegetable", "nonexistent-header"],
function (asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
console.log("Selected headers: " + JSON.stringify(asyncResult.value));
} else {
console.log("Error getting selected headers: " + JSON.stringify(asyncResult.error));
}
}
);
itemType
Gets the type of item that an instance represents.
The itemType
property returns one of the ItemType
enumeration values, indicating whether the item object instance is a message or an appointment.
itemType: MailboxEnums.ItemType | string;
Property Value
Office.MailboxEnums.ItemType | string
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/90-other-item-apis/get-item-type.yaml
const itemType = Office.context.mailbox.item.itemType;
switch (itemType) {
case Office.MailboxEnums.ItemType.Appointment:
console.log(`Current item is an ${itemType}.`);
break;
case Office.MailboxEnums.ItemType.Message:
console.log(`Current item is a ${itemType}. A message could be an email, meeting request, meeting response, or meeting cancellation.`);
break;
}
notificationMessages
Gets the notification messages for an item.
notificationMessages: NotificationMessages;
Property Value
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/35-notifications/add-getall-remove.yaml
// Adds a progress indicator to the mail item.
const id = $("#notificationId").val().toString();
const details =
{
type: Office.MailboxEnums.ItemNotificationMessageType.ProgressIndicator,
message: "Progress indicator with id = " + id
};
Office.context.mailbox.item.notificationMessages.addAsync(id, details, handleResult);
...
// Adds an informational notification to the mail item.
const id = $("#notificationId").val().toString();
const details =
{
type: Office.MailboxEnums.ItemNotificationMessageType.InformationalMessage,
message: "Non-persistent informational notification message with id = " + id,
icon: "icon1",
persistent: false
};
Office.context.mailbox.item.notificationMessages.addAsync(id, details, handleResult);
...
// Adds a persistent information notification to the mail item.
const id = $("#notificationId").val().toString();
const details =
{
type: Office.MailboxEnums.ItemNotificationMessageType.InformationalMessage,
message: "Persistent informational notification message with id = " + id,
icon: "icon1",
persistent: true
};
Office.context.mailbox.item.notificationMessages.addAsync(id, details, handleResult);
...
// Gets all the notification messages and their keys for the current mail item.
Office.context.mailbox.item.notificationMessages.getAllAsync((asyncResult) => {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log(asyncResult.error.message);
return;
}
console.log(asyncResult.value);
});
...
// Replaces a notification message of a given key with another message.
const id = $("#notificationId").val().toString();
Office.context.mailbox.item.notificationMessages.replaceAsync(
id,
{
type: Office.MailboxEnums.ItemNotificationMessageType.InformationalMessage,
message: "Notification message with id = " + id + " has been replaced with an informational message.",
icon: "icon2",
persistent: false
},
handleResult);
...
// Removes a notification message from the current mail item.
const id = $("#notificationId").val().toString();
Office.context.mailbox.item.notificationMessages.removeAsync(id, handleResult);
seriesId
Gets the ID of the series that an instance belongs to.
In Outlook on the web, on Windows (new and classic), and on Mac, the seriesId
returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. However, in Outlook on Android and on iOS, the seriesId returns the REST ID of the parent item.
seriesId: string;
Property Value
string
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Important: The identifier returned by the seriesId
property is the same as the Exchange Web Services item identifier. The seriesId
property is not identical to the Outlook IDs used by the Outlook REST API. Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId
. For more details, see Use the Outlook REST APIs from an Outlook add-in.
The seriesId
property returns null
for items that don't have parent items such as single appointments, series items, or meeting requests and returns undefined
for any other items that are not meeting requests.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/50-recurrence/get-series-id.yaml
const seriesId = Office.context.mailbox.item.seriesId;
if (seriesId === undefined) {
console.log("This is a message that's not a meeting request.");
} else if (seriesId === null) {
console.log("This is a single appointment, a parent series, or a meeting request for a series or single meeting.");
} else {
console.log("This is an instance belonging to series with ID " + seriesId);
}
subject
Gets or sets the description that appears in the subject field of an item.
The subject
property gets or sets the entire subject of the item, as sent by the email server.
The subject
property returns a Subject
object that provides methods to get and set the subject.
subject: Subject;
Property Value
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/90-other-item-apis/get-set-subject-compose.yaml
Office.context.mailbox.item.subject.getAsync((result) => {
if (result.status !== Office.AsyncResultStatus.Succeeded) {
console.error(`Action failed with message ${result.error.message}`);
return;
}
console.log(`Subject: ${result.value}`);
});
...
let subject = "Hello World!";
Office.context.mailbox.item.subject.setAsync(subject, (result) => {
if (result.status !== Office.AsyncResultStatus.Succeeded) {
console.error(`Action failed with message ${result.error.message}`);
return;
}
console.log(`Successfully set subject to ${subject}`);
});
to
Provides access to the recipients on the To line of a message. The type of object and level of access depend on the mode of the current item.
The to
property returns a Recipients
object that provides methods to get or update the recipients on the To line of the message. However, depending on the client/platform (i.e., Windows, Mac, etc.), limits may apply on how many recipients you can get or update. See the Recipients object for more details.
to: Recipients;
Property Value
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
Office.context.mailbox.item.to.setAsync( ['alice@contoso.com', 'bob@contoso.com'] );
Office.context.mailbox.item.to.addAsync( ['jason@contoso.com'] );
Office.context.mailbox.item.to.getAsync(callback);
function callback(asyncResult) {
const arrayOfToRecipients = asyncResult.value;
}
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/30-recipients-and-attendees/get-set-to-message-compose.yaml
Office.context.mailbox.item.to.getAsync(function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
const msgTo = asyncResult.value;
console.log("Message being sent to:");
for (let i = 0; i < msgTo.length; i++) {
console.log(msgTo[i].displayName + " (" + msgTo[i].emailAddress + ")");
}
} else {
console.error(asyncResult.error);
}
});
...
const email = $("#emailTo")
.val()
.toString();
const emailArray = [email];
Office.context.mailbox.item.to.setAsync(emailArray, function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
console.log("Succeeded in setting To field.");
} else {
console.error(asyncResult.error);
}
});
Method Details
addFileAttachmentAsync(uri, attachmentName, options, callback)
Adds a file to a message or appointment as an attachment.
The addFileAttachmentAsync
method uploads the file at the specified URI and attaches it to the item in the compose form.
addFileAttachmentAsync(uri: string, attachmentName: string, options: Office.AsyncContextOptions & { isInline: boolean }, callback?: (asyncResult: Office.AsyncResult<string>) => void): void;
Parameters
- uri
-
string
The URI that provides the location of the file to attach to the message or appointment. The maximum length is 2048 characters.
- attachmentName
-
string
The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters.
- options
-
Office.AsyncContextOptions & { isInline: boolean }
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. isInline
: If true, indicates that the attachment will be shown inline as an image in the message body and won't be displayed in the attachment list.
- 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
. On success, the attachment identifier will be provided in the asyncResult.value
property. If uploading the attachment fails, the asyncResult
object will contain an Error
object that provides a description of the error.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Message Compose
Important:
This method isn't supported in Outlook on iOS or Android. For more information on supported APIs in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
In recent builds of classic Outlook on Windows, a bug was introduced that incorrectly appends an
Authorization: Bearer
header to this action (whether using this API or the Outlook UI). To work around this issue, use theaddFileAttachmentFromBase64
API introduced with requirement set 1.8.The URI of the file to be attached must support caching in production. The server hosting the image shouldn't return a
Cache-Control
header that specifiesno-cache
,no-store
, or similar options in the HTTP response. However, when you're developing the add-in and making changes to files, caching can prevent you from seeing your changes. We recommend usingCache-Control
headers during development.You can use the same URI with the
removeAttachmentAsync
method to remove the attachment in the same session.
Errors:
AttachmentSizeExceeded
: The attachment is larger than allowed.FileTypeNotSupported
: The attachment has an extension that is not allowed.NumberOfAttachmentsExceeded
: The message or appointment has too many attachments.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/40-attachments/attachments-compose.yaml
const attachmentUrl = $("#attachmentUrl")
.val()
.toString();
Office.context.mailbox.item.addFileAttachmentAsync(
attachmentUrl,
getFileName(attachmentUrl),
{ isInline: false },
(result) => {
console.log(result);
}
);
addFileAttachmentAsync(uri, attachmentName, callback)
Adds a file to a message or appointment as an attachment.
The addFileAttachmentAsync
method uploads the file at the specified URI and attaches it to the item in the compose form.
addFileAttachmentAsync(uri: string, attachmentName: string, callback?: (asyncResult: Office.AsyncResult<string>) => void): void;
Parameters
- uri
-
string
The URI that provides the location of the file to attach to the message or appointment. The maximum length is 2048 characters.
- attachmentName
-
string
The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters.
- 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
. On success, the attachment identifier will be provided in the asyncResult.value
property. If uploading the attachment fails, the asyncResult
object will contain an Error
object that provides a description of the error.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Message Compose
Important:
This method isn't supported in Outlook on iOS or Android. For more information on supported APIs in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
In recent builds of classic Outlook on Windows, a bug was introduced that incorrectly appends an
Authorization: Bearer
header to this action (whether using this API or the Outlook UI). To work around this issue, use theaddFileAttachmentFromBase64
API introduced with requirement set 1.8.The URI of the file to be attached must support caching in production. The server hosting the image shouldn't return a
Cache-Control
header that specifiesno-cache
,no-store
, or similar options in the HTTP response. However, when you're developing the add-in and making changes to files, caching can prevent you from seeing your changes. We recommend usingCache-Control
headers during development.You can use the same URI with the
removeAttachmentAsync
method to remove the attachment in the same session.
Errors:
AttachmentSizeExceeded
: The attachment is larger than allowed.FileTypeNotSupported
: The attachment has an extension that is not allowed.NumberOfAttachmentsExceeded
: The message or appointment has too many attachments.
addFileAttachmentFromBase64Async(base64File, attachmentName, options, callback)
Adds a file to a message or appointment as an attachment.
The addFileAttachmentFromBase64Async
method uploads the file from the Base64 encoding and attaches it to the item in the compose form. This method returns the attachment identifier in the asyncResult.value
object.
You can subsequently use the identifier with the removeAttachmentAsync
method to remove the attachment in the same session.
addFileAttachmentFromBase64Async(base64File: string, attachmentName: string, options: Office.AsyncContextOptions & { isInline: boolean }, callback?: (asyncResult: Office.AsyncResult<string>) => void): void;
Parameters
- base64File
-
string
The Base64-encoded content of an image or file to be added to an email or event. The maximum length of the encoded string is 27,892,122 characters (about 25 MB).
- attachmentName
-
string
The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters.
- options
-
Office.AsyncContextOptions & { isInline: boolean }
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. isInline
: If true, indicates that the attachment will be shown inline as an image in the message body and won't be displayed in the attachment list.
- 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. On success, the attachment identifier will be provided in the asyncResult.value
property. If uploading the attachment fails, the asyncResult
object will contain an Error
object that provides a description of the error.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Message Compose
Important:
Adding an inline Base64 file to a message in compose mode is supported in Outlook on Android and on iOS. For more information on supported APIs in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
If you're using a data URL API (for example,
readAsDataURL
), you need to strip out the data URL prefix, then send the rest of the string to this API. For example, if the full string is represented bydata:image/svg+xml;base64,<rest of Base64 string>
, removedata:image/svg+xml;base64,
.If you're adding an inline Base64 image to the body of a message or appointment being composed, you must first get the current item body using the Office.context.mailbox.item.body.getAsync method before inserting the image using
addFileAttachmentFromBase64Async
. Otherwise, the image won't render in the body once it's inserted. For further guidance, see Attach a file.
Errors:
AttachmentSizeExceeded
: The attachment is larger than allowed.FileTypeNotSupported
: The attachment has an extension that isn't allowed.NumberOfAttachmentsExceeded
: The message or appointment has too many attachments.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/40-attachments/attachments-compose.yaml
const base64String =
"iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsSAAALEgHS3X78AAACRUlEQVRYw82XzXHbMBCFP2F8tzsQc8Ixyh0zoiuIXIGdCsxUYKqC0B04FdiuwMoM7mGOOIXqQGoAymXhgSX+itJM9kIRFLAP+3YXD5Pdbscx5oxaAIW8Ztr6l2PWmQwF4IyaieP53qdfAqQ8CwBn1JU4vpWhrbxXQA5MZfynANmcDIAzKgcy4FKGXsVJFf3nLgKyBQptfT4KQMRz2N0fcbxqmRMDWXflx0VPnrdArq0vekQ1Dv0UeHZGNebHhwjU8AzwKM43RyZnbAf58Q6ghudeWd0Aus0+5EcMIIRi3beua0D3Nm39BEAx3i7HTK4DEBJn5YxKOnaRA5+ErpMBWMpzDvx1RuXCcxOISlufAjfC7zgAsqsvUvMAD0ApPaEtGi9AIlUzKgJo60tt/SyKRkzLrAXERluf7W1gOICWaMyB386oooOWsIHvXbSoHuUSFovtHqicUVnH3EJoeT0aQEf5/XBGlc6otIOWBXAtPeZkAIJ9Bt6cUU9tZautX2nrk3MACHYr1ZKProKRtDw4o8pzAPjWo+NtpXTTvoteDDg8noDAcwbcRedAkGdFXyk2GEDcegVAFp2gyVDHjRQ4o6q2smoqtR5Hd+qMqtoALCWUUymr1m43QMZfOaMK4C0SrMsDANJ2E5FNcbdbjHC+ENl+H0myJFbLtaq4Rt8dyPBYRQV1E40nMv9rl7xrOw3DGb+Whcqu3i/OM6CUOWvgRlufNmnLYy4m77uJI7AXtdNcTDrU71LEyv7v01/N/ovL6bmu5/8A1tNWZldH0W4AAAAASUVORK5CYII=";
Office.context.mailbox.item.addFileAttachmentFromBase64Async(
base64String,
"logo.png",
{ isInline: false },
(result) => {
console.log(result);
}
);
...
// 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}`);
}
}
);
addFileAttachmentFromBase64Async(base64File, attachmentName, callback)
Adds a file to a message or appointment as an attachment.
The addFileAttachmentFromBase64Async
method uploads the file from the Base64 encoding and attaches it to the item in the compose form. This method returns the attachment identifier in the asyncResult.value
object.
You can subsequently use the identifier with the removeAttachmentAsync
method to remove the attachment in the same session.
addFileAttachmentFromBase64Async(base64File: string, attachmentName: string, callback?: (asyncResult: Office.AsyncResult<string>) => void): void;
Parameters
- base64File
-
string
The Base64-encoded content of an image or file to be added to an email or event. The maximum length of the encoded string is 27,892,122 characters (about 25 MB).
- attachmentName
-
string
The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters.
- 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. On success, the attachment identifier will be provided in the asyncResult.value
property. If uploading the attachment fails, the asyncResult
object will contain an Error
object that provides a description of the error.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Message Compose
Important:
Adding an inline Base64 file to a message in compose mode is supported in Outlook on Android and on iOS. For more information on supported APIs in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
If you're using a data URL API (for example,
readAsDataURL
), you need to strip out the data URL prefix, then send the rest of the string to this API. For example, if the full string is represented bydata:image/svg+xml;base64,<rest of Base64 string>
, removedata:image/svg+xml;base64,
.If you're adding an inline Base64 image to the body of a message or appointment being composed, you must first get the current item body using the Office.context.mailbox.item.body.getAsync method before inserting the image using
addFileAttachmentFromBase64Async
. Otherwise, the image won't render in the body once it's inserted. For further guidance, see Attach a file.
Errors:
AttachmentSizeExceeded
: The attachment is larger than allowed.FileTypeNotSupported
: The attachment has an extension that isn't allowed.NumberOfAttachmentsExceeded
: The message or appointment has too many attachments.
addHandlerAsync(eventType, handler, options, callback)
Adds an event handler for a supported event. Note: Events are only available with task pane implementation.
For supported events, refer to the Item object model events section.
addHandlerAsync(eventType: Office.EventType | string, handler: any, options: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- eventType
-
Office.EventType | string
The event that should invoke the handler.
- handler
-
any
The function to handle the event. The function must accept a single parameter, which is an object literal. The type
property on the parameter will match the eventType
parameter passed to addHandlerAsync
.
- 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<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter, asyncResult
, which is an Office.AsyncResult
object.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
function myHandlerFunction(eventarg) {
if (eventarg.attachmentStatus === Office.MailboxEnums.AttachmentStatus.Added) {
const attachment = eventarg.attachmentDetails;
console.log("Event Fired and Attachment Added!");
getAttachmentContentAsync(attachment.id, options, callback);
}
}
Office.context.mailbox.item.addHandlerAsync(Office.EventType.AttachmentsChanged, myHandlerFunction, myCallback);
addHandlerAsync(eventType, handler, callback)
Adds an event handler for a supported event. Note: Events are only available with task pane implementation.
For supported events, refer to the Item object model events section.
addHandlerAsync(eventType: Office.EventType | string, handler: any, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- eventType
-
Office.EventType | string
The event that should invoke the handler.
- handler
-
any
The function to handle the event. The function must accept a single parameter, which is an object literal. The type
property on the parameter will match the eventType
parameter passed to addHandlerAsync
.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter, asyncResult
, which is an Office.AsyncResult
object.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
addItemAttachmentAsync(itemId, attachmentName, options, callback)
Adds an Exchange item, such as a message, as an attachment to the message or appointment.
The addItemAttachmentAsync
method attaches the item with the specified Exchange identifier to the item in the compose form. If you specify a callback function, the method is called with one parameter, asyncResult
, which contains either the attachment identifier or a code that indicates any error that occurred while attaching the item. You can use the options parameter to pass state information to the callback function, if needed.
You can subsequently use the identifier with the removeAttachmentAsync
method to remove the attachment in the same session.
If your Office Add-in is running in Outlook on the web or new Outlook on Windows, the addItemAttachmentAsync
method can attach items to items other than the item that you are editing. However, this isn't supported and isn't recommended.
addItemAttachmentAsync(itemId: any, attachmentName: string, options: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult<string>) => void): void;
Parameters
- itemId
-
any
The Exchange identifier of the item to attach. The maximum length is 100 characters.
- attachmentName
-
string
The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters.
- 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
. On success, the attachment identifier will be provided in the asyncResult.value
property. If adding the attachment fails, the asyncResult
object will contain an Error
object that provides a description of the error.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Message Compose
Errors:
NumberOfAttachmentsExceeded
: The message or appointment has too many attachments.
Examples
// The following example adds an existing Outlook item as an attachment
// with the name "My Attachment".
function addAttachment() {
// EWS ID of item to attach (shortened for readability).
const itemId = "AAMkADI1...AAA=";
// The values in asyncContext can be accessed in the callback.
const options = { asyncContext: { var1: 1, var2: 2 } };
Office.context.mailbox.item.addItemAttachmentAsync(itemId, "My Attachment", options, (result) => {
if (result.status === Office.AsyncResultStatus.Failed) {
console.error("Failed to add attachment: " + result.error.message);
return;
}
console.log("Attachment added successfully.");
console.log("var1: " + result.asyncContext.var1);
console.log("var2: " + result.asyncContext.var2);
});
}
addItemAttachmentAsync(itemId, attachmentName, callback)
Adds an Exchange item, such as a message, as an attachment to the message or appointment.
The addItemAttachmentAsync
method attaches the item with the specified Exchange identifier to the item in the compose form. If you specify a callback function, the method is called with one parameter, asyncResult
, which contains either the attachment identifier or a code that indicates any error that occurred while attaching the item. You can use the options parameter to pass state information to the callback function, if needed.
You can subsequently use the identifier with the removeAttachmentAsync
method to remove the attachment in the same session.
If your Office Add-in is running in Outlook on the web or new Outlook on Windows, the addItemAttachmentAsync
method can attach items to items other than the item that you are editing. However, this isn't supported and isn't recommended.
addItemAttachmentAsync(itemId: any, attachmentName: string, callback?: (asyncResult: Office.AsyncResult<string>) => void): void;
Parameters
- itemId
-
any
The Exchange identifier of the item to attach. The maximum length is 100 characters.
- attachmentName
-
string
The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters.
- 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
. On success, the attachment identifier will be provided in the asyncResult.value
property. If adding the attachment fails, the asyncResult
object will contain an Error
object that provides a description of the error.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Message Compose
Errors:
NumberOfAttachmentsExceeded
: The message or appointment has too many attachments.
close()
Closes the current item that is being composed.
The behavior of the close
method depends on the current state of the item being composed. If the item has unsaved changes, the client prompts the user to save, discard, or close the action.
In Outlook on Windows (classic) and on Mac, the close
method has no effect on a reply in the Reading Pane.
close(): void;
Returns
void
Remarks
Minimum permission level: restricted
Applicable Outlook mode: Message Compose
Important: In Outlook on the web and new Outlook on Windows, if the item is an appointment and it has previously been saved using saveAsync
, the user is prompted to save, discard, or cancel even if no changes have occurred since the item was last saved.
Tip: Use the closeAsync method instead of the close
method if you want your add-in to:
Automatically discard a message being composed without prompting the user with the save dialog.
Determine when a user cancels the save item dialog on a message being composed.
Close a reply in the Reading Pane or an existing draft.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/25-item-save-and-close/close.yaml
Office.context.mailbox.item.close();
disableClientSignatureAsync(options, callback)
Disables the Outlook client signature.
The behavior of this method depends on which client the add-in is running.
In Outlook on the web and new Outlook on Windows, the signature option for new mails, replies, and forwards is disabled. A signature that's selected is also disabled by the method.
In Outlook on Windows (classic) and on Mac, the signature under the New messages and Replies/forwards sections of the sending account is set to (none).
In Outlook on Android and on iOS, the signature saved on the mobile device is cleared.
disableClientSignatureAsync(options: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult<void>) => 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<void>) => void
Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult
, which is an Office.AsyncResult
object.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Message Compose
Important: This method is supported in Message Compose on Outlook on Android and on iOS starting in Version 4.2352.0. 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/90-other-item-apis/work-with-client-signatures.yaml
// Disable the client signature.
Office.context.mailbox.item.disableClientSignatureAsync(function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
console.log("disableClientSignatureAsync succeeded");
} else {
console.error(asyncResult.error);
}
});
disableClientSignatureAsync(callback)
Disables the Outlook client signature.
The behavior of this method depends on which client the add-in is running.
In Outlook on the web and new Outlook on Windows, the signature option for new mails, replies, and forwards is disabled. A signature that's selected is also disabled by the method.
In Outlook on Windows (classic) and on Mac, the signature under the New messages and Replies/forwards sections of the sending account is set to (none).
In Outlook on Android and on iOS, the signature saved on the mobile device is cleared.
disableClientSignatureAsync(callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult
, which is an Office.AsyncResult
object.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Message Compose
Important: This method is supported in Message Compose on Outlook on Android and on iOS starting in Version 4.2352.0. For more information on supported APIs in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
getAttachmentContentAsync(attachmentId, options, callback)
Gets an attachment from a message or appointment and returns it as an AttachmentContent
object.
The getAttachmentContentAsync
method gets the attachment with the specified identifier from the item. As a best practice, you should get the attachment's identifier from a getAttachmentsAsync
call, then in the same session, use that identifier to retrieve the attachment. In Outlook on the web, on mobile devices, and in new Outlook on Windows, the attachment identifier is valid only within the same session. A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to continue in a separate window.
getAttachmentContentAsync(attachmentId: string, options: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult<AttachmentContent>) => void): void;
Parameters
- attachmentId
-
string
The identifier of the attachment you want to get.
- 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.AttachmentContent>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter, asyncResult
, which is an Office.AsyncResult
object. If the call fails, the asyncResult.error
property will contain an error code with the reason for the failure.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Errors:
AttachmentTypeNotSupported
: The attachment type isn't supported. Unsupported types include embedded images in Rich Text Format, or item attachment types other than email or calendar items (such as a contact or task item).InvalidAttachmentId
: The attachment identifier does not exist.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/40-attachments/get-attachment-content.yaml
// Gets the attachments of the current message or appointment in compose mode.
const options = { asyncContext: { currentItem: item } };
// The getAttachmentsAsync call can only be used in compose mode.
item.getAttachmentsAsync(options, callback);
function callback(result) {
if (result.status === Office.AsyncResultStatus.Failed) {
console.log(result.error.message);
return;
}
if (result.value.length <= 0) {
console.log("Mail item has no attachments.");
return;
}
for (let i = 0; i < result.value.length; i++) {
// Log the attachment type and its contents to the console.
result.asyncContext.currentItem.getAttachmentContentAsync(result.value[i].id, handleAttachmentsCallback);
}
}
getAttachmentContentAsync(attachmentId, callback)
Gets an attachment from a message or appointment and returns it as an AttachmentContent
object.
The getAttachmentContentAsync
method gets the attachment with the specified identifier from the item. As a best practice, you should get the attachment's identifier from a getAttachmentsAsync
call, then in the same session, use that identifier to retrieve the attachment. In Outlook on the web, on mobile devices, and in new Outlook on Windows, the attachment identifier is valid only within the same session. A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to continue in a separate window.
getAttachmentContentAsync(attachmentId: string, callback?: (asyncResult: Office.AsyncResult<AttachmentContent>) => void): void;
Parameters
- attachmentId
-
string
The identifier of the attachment you want to get.
- callback
-
(asyncResult: Office.AsyncResult<Office.AttachmentContent>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter, asyncResult
, which is an Office.AsyncResult
object. If the call fails, the asyncResult.error
property will contain an error code with the reason for the failure.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Errors:
AttachmentTypeNotSupported
: The attachment type isn't supported. Unsupported types include embedded images in Rich Text Format, or item attachment types other than email or calendar items (such as a contact or task item).InvalidAttachmentId
: The attachment identifier does not exist.
getAttachmentsAsync(options, callback)
Gets the item's attachments as an array.
getAttachmentsAsync(options: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult<AttachmentDetailsCompose[]>) => 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.AttachmentDetailsCompose[]>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. If the call fails, the asyncResult.error
property will contain an error code with the reason for the failure.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/40-attachments/attachments-compose.yaml
Office.context.mailbox.item.getAttachmentsAsync((result) => {
if (result.status === Office.AsyncResultStatus.Failed) {
console.error(result.error.message);
return;
}
if (result.value.length > 0) {
for (let i = 0; i < result.value.length; i++) {
const attachment = result.value[i];
let attachmentType;
switch (attachment.attachmentType) {
case Office.MailboxEnums.AttachmentType.Cloud:
attachmentType = "Attachment is stored in a cloud location";
break;
case Office.MailboxEnums.AttachmentType.File:
attachmentType = "Attachment is a file";
break;
case Office.MailboxEnums.AttachmentType.Item:
attachmentType = "Attachment is an Exchange item";
break;
}
console.log(
"ID: " +
attachment.id +
"\n" +
"Type: " +
attachmentType +
"\n" +
"Name: " +
attachment.name +
"\n" +
"Size: " +
attachment.size +
"\n" +
"isInline: " +
attachment.isInline
);
}
} else {
console.log("No attachments on this message.");
}
});
getAttachmentsAsync(callback)
Gets the item's attachments as an array.
getAttachmentsAsync(callback?: (asyncResult: Office.AsyncResult<AttachmentDetailsCompose[]>) => void): void;
Parameters
- callback
-
(asyncResult: Office.AsyncResult<Office.AttachmentDetailsCompose[]>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. If the call fails, the asyncResult.error
property will contain an error code with the reason for the failure.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
getComposeTypeAsync(options, callback)
Specifies the type of message compose and its coercion type. The message can be new, or a reply or forward. The coercion type can be HTML or plain text.
getComposeTypeAsync(options: Office.AsyncContextOptions, callback: (asyncResult: Office.AsyncResult<any>) => 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<any>) => void
When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. On success, the asyncResult.value
property contains an object with the item's compose type and coercion type.
Returns
void
An object with ComposeType
and CoercionType
enum values for the message item.
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Important: This method is supported in Outlook on Android and on iOS starting in Version 4.2352.0. For more information on supported APIs in Outlook mobile, see Outlook JavaScript APIs supported in Outlook on mobile devices.
getComposeTypeAsync(callback)
Specifies the type of message compose and its coercion type. The message can be new, or a reply or forward. The coercion type can be HTML or plain text.
getComposeTypeAsync(callback: (asyncResult: Office.AsyncResult<any>) => void): void;
Parameters
- callback
-
(asyncResult: Office.AsyncResult<any>) => void
When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. On success, the asyncResult.value
property contains an object with the item's compose type and coercion type.
Returns
void
An object with ComposeType
and CoercionType
enum values for the message item.
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Important: This method is supported in Outlook on Android and on iOS starting in Version 4.2352.0. 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/90-other-item-apis/work-with-client-signatures.yaml
// Get the compose type of the current message.
Office.context.mailbox.item.getComposeTypeAsync(function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
console.log(
"getComposeTypeAsync succeeded with composeType: " +
asyncResult.value.composeType +
" and coercionType: " +
asyncResult.value.coercionType
);
} else {
console.error(asyncResult.error);
}
});
getInitializationContextAsync(options, callback)
Gets initialization data passed when the add-in is activated by an actionable message.
getInitializationContextAsync(options: Office.AsyncContextOptions, callback: (asyncResult: Office.AsyncResult<string>) => 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<string>) => void
When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. On success, the initialization context data is provided as a string (or an empty string if there's no initialization context) in the asyncResult.value
property.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
// Get the initialization context (if present).
Office.context.mailbox.item.getInitializationContextAsync((asyncResult) => {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
if (asyncResult.value.length > 0) {
// The value is a string, parse to an object.
const context = JSON.parse(asyncResult.value);
// Do something with context.
} else {
// Empty context, treat as no context.
}
} else {
// Handle the error.
}
});
getInitializationContextAsync(callback)
Gets initialization data passed when the add-in is activated by an actionable message.
getInitializationContextAsync(callback: (asyncResult: Office.AsyncResult<string>) => void): void;
Parameters
- callback
-
(asyncResult: Office.AsyncResult<string>) => void
When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. On success, the initialization context data is provided as a string (or an empty string if there's no initialization context) in the asyncResult.value
property.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
getItemIdAsync(options, callback)
Asynchronously gets the Exchange Web Services (EWS) item identifier of a saved item.
When invoked, this method returns the item ID via the callback function.
getItemIdAsync(options: Office.AsyncContextOptions, callback: (asyncResult: Office.AsyncResult<string>) => 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<string>) => void
When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. The EWS item ID of the item is returned in the asyncResult.value
property.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Important:
The item ID returned isn't identical to the Outlook Entry ID or the ID used by the Outlook REST API. Before making REST API calls using this value, it should be converted using
Office.context.mailbox.convertToRestId
.If your add-in calls
getItemIdAsync
(for example, to get an item ID to use with EWS or the REST API), be aware that when Outlook is in cached mode, it may take some time before the item is synced to the server. Until the item is synced, the item ID isn't recognized and using it returns an error.
Errors:
ItemNotSaved
: The ID can't be retrieved until the item is saved.
getItemIdAsync(callback)
Asynchronously gets the Exchange Web Services (EWS) item identifier of a saved item.
When invoked, this method returns the item ID via the callback function.
getItemIdAsync(callback: (asyncResult: Office.AsyncResult<string>) => void): void;
Parameters
- callback
-
(asyncResult: Office.AsyncResult<string>) => void
When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. The EWS item ID of the item is returned in the asyncResult.value
property.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Important:
The item ID returned isn't identical to the Outlook Entry ID or the ID used by the Outlook REST API. Before making REST API calls using this value, it should be converted using
Office.context.mailbox.convertToRestId
.If your add-in calls
getItemIdAsync
(for example, to get an item ID to use with EWS or the REST API), be aware that when Outlook is in cached mode, it may take some time before the item is synced to the server. Until the item is synced, the item ID isn't recognized and using it returns an error.
Errors:
ItemNotSaved
: The ID can't be retrieved until the item is saved.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/90-other-item-apis/item-id-compose.yaml
Office.context.mailbox.item.getItemIdAsync((result) => {
if (result.status === Office.AsyncResultStatus.Failed) {
console.error(`getItemIdAsync failed with message: ${result.error.message}`);
return;
}
console.log(result.value);
});
getSelectedDataAsync(coercionType, options, callback)
Asynchronously returns selected data from the subject or body of a message.
If there is no selection but the cursor is in the body or subject, the method returns an empty string for the selected data. If a field other than the body or subject is selected, the method returns the InvalidSelection
error.
To access the selected data from the callback function, call asyncResult.value.data
. To access the source property that the selection comes from, call asyncResult.value.sourceProperty
, which will be either body
or subject
.
getSelectedDataAsync(coercionType: Office.CoercionType | string, options: Office.AsyncContextOptions, callback: (asyncResult: Office.AsyncResult<any>) => void): void;
Parameters
- coercionType
-
Office.CoercionType | string
Requests a format for the data. If Text
, the method returns the plain text as a string, removing any HTML tags present. If Html
, the method returns the selected text, whether it is plaintext or HTML.
- 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<any>) => void
When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
.
Returns
void
The selected data as a string with format determined by coercionType
.
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
// Get selected data.
Office.context.mailbox.item.getSelectedDataAsync(Office.CoercionType.Text, { option1: "option1"}, getCallback);
function getCallback(asyncResult) {
const text = asyncResult.value.data;
const prop = asyncResult.value.sourceProperty;
console.log(`Selected text in ${prop}: ${text}`);
}
getSelectedDataAsync(coercionType, callback)
Asynchronously returns selected data from the subject or body of a message.
If there is no selection but the cursor is in the body or subject, the method returns an empty string for the selected data. If a field other than the body or subject is selected, the method returns the InvalidSelection
error.
To access the selected data from the callback function, call asyncResult.value.data
. To access the source property that the selection comes from, call asyncResult.value.sourceProperty
, which will be either body
or subject
.
getSelectedDataAsync(coercionType: Office.CoercionType | string, callback: (asyncResult: Office.AsyncResult<any>) => void): void;
Parameters
- coercionType
-
Office.CoercionType | string
Requests a format for the data. If Text
, the method returns the plain text as a string, removing any HTML tags present. If Html
, the method returns the selected text, whether it is plaintext or HTML.
- callback
-
(asyncResult: Office.AsyncResult<any>) => void
When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
.
Returns
void
The selected data as a string with format determined by coercionType
.
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/20-item-body/get-selected-data.yaml
Office.context.mailbox.item.getSelectedDataAsync(Office.CoercionType.Text, function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
const text = asyncResult.value.data;
const prop = asyncResult.value.sourceProperty;
console.log("Selected text in " + prop + ": " + text);
} else {
console.error(asyncResult.error);
}
});
getSharedPropertiesAsync(options, callback)
Gets the properties of an appointment or message in a shared folder or shared mailbox.
For more information around using this API, see Enable shared folders and shared mailbox scenarios in an Outlook add-in.
getSharedPropertiesAsync(options: Office.AsyncContextOptions, callback: (asyncResult: Office.AsyncResult<SharedProperties>) => 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.SharedProperties>) => void
When the method completes, the function passed in the callback
parameter is called with a single parameter, asyncResult
, which is an Office.AsyncResult
object. The asyncResult.value
property provides the properties of the shared item.
Returns
void
Remarks
[ API set: Mailbox 1.8 for shared folder support, Mailbox 1.13 for shared mailbox support ]
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Note: This method isn't supported in Outlook on iOS or on Android.
Important: In Message Compose mode, this API isn't supported in Outlook on the web or on Windows (new and classic) unless the following conditions are met.
a. Delegate access/Shared folders
The mailbox owner starts a message. This can be a new message, a reply, or a forward.
They save the message then move it from their own Drafts folder to a folder shared with the delegate.
The delegate opens the draft from the shared folder then continues composing.
b. Shared mailbox (applies to classic Outlook on Windows only)
The shared mailbox user starts a message. This can be a new message, a reply, or a forward.
They save the message then move it from their own Drafts folder to a folder in the shared mailbox.
Another shared mailbox user opens the draft from the shared mailbox then continues composing.
The message is now in a shared context and add-ins that support these shared scenarios can get the item's shared properties. After the message has been sent, it's usually found in the sender's Sent Items folder.
getSharedPropertiesAsync(callback)
Gets the properties of an appointment or message in a shared folder or shared mailbox.
For more information around using this API, see Enable shared folders and shared mailbox scenarios in an Outlook add-in.
getSharedPropertiesAsync(callback: (asyncResult: Office.AsyncResult<SharedProperties>) => void): void;
Parameters
- callback
-
(asyncResult: Office.AsyncResult<Office.SharedProperties>) => void
When the method completes, the function passed in the callback
parameter is called with a single parameter, asyncResult
, which is an Office.AsyncResult
object. The asyncResult.value
property provides the properties of the shared item.
Returns
void
Remarks
[ API set: Mailbox 1.8 for shared folder support, Mailbox 1.13 for shared mailbox support ]
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Note: This method isn't supported in Outlook on iOS or on Android.
Important: In Message Compose mode, this API isn't supported in Outlook on the web or on Windows (new and classic) unless the following conditions are met.
a. Delegate access/Shared folders
The mailbox owner starts a message. This can be a new message, a reply, or a forward.
They save the message then move it from their own Drafts folder to a folder shared with the delegate.
The delegate opens the draft from the shared folder then continues composing.
b. Shared mailbox (applies to classic Outlook on Windows only)
The shared mailbox user starts a message. This can be a new message, a reply, or a forward.
They save the message then move it from their own Drafts folder to a folder in the shared mailbox.
Another shared mailbox user opens the draft from the shared mailbox then continues composing.
The message is now in a shared context and add-ins that support these shared scenarios can get the item's shared properties. After the message has been sent, it's usually found in the sender's Sent Items folder.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/65-delegates-and-shared-folders/get-shared-properties.yaml
Office.context.mailbox.item.getSharedPropertiesAsync((result) => {
if (result.status === Office.AsyncResultStatus.Failed) {
console.error("The current folder or mailbox isn't shared.");
return;
}
const sharedProperties = result.value;
console.log(`Owner: ${sharedProperties.owner}`);
console.log(`Permissions: ${sharedProperties.delegatePermissions}`);
console.log(`Target mailbox: ${sharedProperties.targetMailbox}`);
});
isClientSignatureEnabledAsync(options, callback)
Gets if the client signature is enabled.
In Outlook on Windows (classic) and on Mac, the API call returns true
if the default signature for new messages, replies, or forwards is set to a template for the sending Outlook account. In Outlook on the web and new Outlook on Windows, the API call returns true
if the signature is enabled for compose types newMail
, reply
, or forward
. If the settings are set to "(none)" in Outlook on Windows (classic) or on Mac, or disabled in Outlook on the web or new Outlook on Windows, the API call returns false
.
isClientSignatureEnabledAsync(options: Office.AsyncContextOptions, callback: (asyncResult: Office.AsyncResult<boolean>) => 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<boolean>) => void
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 item
Applicable Outlook mode: Message Compose
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
// Check if the client signature is currently enabled.
Office.context.mailbox.item.isClientSignatureEnabledAsync(function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
console.log("isClientSignatureEnabledAsync succeeded with result: " + asyncResult.value);
} else {
console.error(asyncResult.error);
}
});
isClientSignatureEnabledAsync(callback)
Gets if the client signature is enabled.
In Outlook on Windows (classic) and on Mac, the API call returns true
if the default signature for new messages, replies, or forwards is set to a template for the sending Outlook account. In Outlook on the web and new Outlook on Windows, the API call returns true
if the signature is enabled for compose types newMail
, reply
, or forward
. If the settings are set to "(none)" in Outlook on Windows (classic) or on Mac, or disabled in Outlook on the web or new Outlook on Windows, the API call returns false
.
isClientSignatureEnabledAsync(callback: (asyncResult: Office.AsyncResult<boolean>) => void): void;
Parameters
- callback
-
(asyncResult: Office.AsyncResult<boolean>) => void
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 item
Applicable Outlook mode: Message Compose
loadCustomPropertiesAsync(callback, userContext)
Asynchronously loads custom properties for this add-in on the selected item.
Custom properties are stored as key-value pairs on a per-app, per-item basis. This method returns a CustomProperties object in the callback, which provides methods to access the custom properties specific to the current item and the current add-in. Custom properties aren't encrypted on the item, so this shouldn't be used as secure storage.
The custom properties are provided as a CustomProperties
object in the asyncResult.value
property. This object can be used to get, set, save, and remove custom properties from the mail item.
loadCustomPropertiesAsync(callback: (asyncResult: Office.AsyncResult<CustomProperties>) => void, userContext?: any): void;
Parameters
- callback
-
(asyncResult: Office.AsyncResult<Office.CustomProperties>) => void
When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
.
- userContext
-
any
Optional. Developers can provide any object they wish to access in the callback function. This object can be accessed by the asyncResult.asyncContext
property in the callback function.
Returns
void
Remarks
To learn more about custom properties, see Get and set add-in metadata for an Outlook add-in.
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/15-item-custom-properties/load-set-get-save.yaml
Office.context.mailbox.item.loadCustomPropertiesAsync((result) => {
if (result.status === Office.AsyncResultStatus.Failed) {
console.error(`loadCustomPropertiesAsync failed with message ${result.error.message}`);
return;
}
customProps = result.value;
console.log("Loaded the CustomProperties object.");
});
removeAttachmentAsync(attachmentId, options, callback)
Removes an attachment from a message or appointment.
The removeAttachmentAsync
method removes the attachment with the specified identifier from the item. As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment in the same session. In Outlook on the web, on mobile devices, and in new Outlook on Windows, the attachment identifier is valid only within the same session. A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to continue in a separate window.
removeAttachmentAsync(attachmentId: string, options: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- attachmentId
-
string
The identifier of the attachment to remove. The maximum string length of the attachmentId
is 200 characters in Outlook on the web and on Windows (new and classic).
- 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<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter of type Office.AsyncResult
. If removing the attachment fails, the asyncResult.error
property will contain an error code with the reason for the failure.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Message Compose
Important*: The removeAttachmentAsync
method doesn't remove inline attachments from a mail item. To remove an inline attachment, first get the item's body, then remove any references of the attachment from its contents. Use the Office.Body APIs to get and set the body of an item.
Errors:
InvalidAttachmentId
: The attachment identifier does not exist.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/40-attachments/attachments-compose.yaml
Office.context.mailbox.item.removeAttachmentAsync(
$("#attachmentId")
.val()
.toString(),
(result) => {
if (result.status === Office.AsyncResultStatus.Failed) {
console.error(result.error.message);
return;
}
console.log(`Attachment removed successfully.`);
}
);
removeAttachmentAsync(attachmentId, callback)
Removes an attachment from a message or appointment.
The removeAttachmentAsync
method removes the attachment with the specified identifier from the item. As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment in the same session. In Outlook on the web, on mobile devices, and in new Outlook on Windows, the attachment identifier is valid only within the same session. A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to continue in a separate window.
removeAttachmentAsync(attachmentId: string, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- attachmentId
-
string
The identifier of the attachment to remove. The maximum string length of the attachmentId
is 200 characters in Outlook on the web and on Windows (new and classic).
- 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
. If removing the attachment fails, the asyncResult.error
property will contain an error code with the reason for the failure.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Message Compose
Important*: The removeAttachmentAsync
method doesn't remove inline attachments from a mail item. To remove an inline attachment, first get the item's body, then remove any references of the attachment from its contents. Use the Office.Body APIs to get and set the body of an item.
Errors:
InvalidAttachmentId
: The attachment identifier does not exist.
removeHandlerAsync(eventType, options, callback)
Removes the event handlers for a supported event type. Note: Events are only available with task pane implementation.
For supported events, refer to the Item object model events section.
removeHandlerAsync(eventType: Office.EventType | string, options: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- eventType
-
Office.EventType | string
The event that should revoke the handler.
- 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<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter, asyncResult
, which is an Office.AsyncResult
object.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
removeHandlerAsync(eventType, callback)
Removes the event handlers for a supported event type. Note: Events are only available with task pane implementation.
For supported events, refer to the Item object model events section.
removeHandlerAsync(eventType: Office.EventType | string, callback?: (asyncResult: Office.AsyncResult<void>) => void): void;
Parameters
- eventType
-
Office.EventType | string
The event that should revoke the handler.
- callback
-
(asyncResult: Office.AsyncResult<void>) => void
Optional. When the method completes, the function passed in the callback
parameter is called with a single parameter, asyncResult
, which is an Office.AsyncResult
object.
Returns
void
Remarks
Minimum permission level: read item
Applicable Outlook mode: Message Compose
Examples
Office.context.mailbox.item.removeHandlerAsync(Office.EventType.ItemChanged, (asyncResult) => {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.error("Failed to remove event handler: " + asyncResult.error.message);
return;
}
console.log("Event handler removed successfully.");
});
saveAsync(options, callback)
Asynchronously saves the current message as a draft.
saveAsync(options: Office.AsyncContextOptions, callback: (asyncResult: Office.AsyncResult<string>) => 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<string>) => void
When the method completes, the function passed in the callback
parameter is called with a single parameter, asyncResult
, which is an Office.AsyncResult
object. The EWS message ID is returned in the asyncResult.value
property.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Message Compose
Important:
In Outlook on the web, new Outlook on Windows, or classic Outlook on Windows in online mode (non-cached mode), the item is saved to the server. In Outlook in cached mode, the item is saved to the local cache.
When working with HTML-formatted content, it's important to note that the Outlook client may modify the content. This means that subsequent calls to methods like
Body.getAsync
,Body.setAsync
, and evensaveAsync
may not result in the same content.The identifier returned is the same as the Exchange Web Services (EWS) item identifier. The item ID returned isn't identical to the Outlook Entry ID or the ID used by the Outlook REST API. Before making REST API calls using this value, it should be converted using
Office.context.mailbox.convertToRestId
.If your add-in calls
saveAsync
to get an item ID to use with EWS or the REST API, be aware that when Outlook is in cached mode, it may take some time before the item is actually synced to the server. Until the item is synced, using the item ID will return an error.In Outlook on the web and new Outlook on Windows, the mailbox account to which a draft is saved varies when
saveAsync
is called on a message that will be sent from a shared mailbox account. If the sender creates a new message from their personal mailbox and selects the shared mailbox account in the From field,saveAsync
saves the draft to the Drafts folder of the user's personal mailbox. If the sender opens the shared mailbox account in a separate browser tab (through the Open another mailbox option, for example) and creates a new message there,saveAsync
saves the draft to the Drafts folder of the shared mailbox.
Errors:
InvalidAttachmentId
: The attachment identifier does not exist.
saveAsync(callback)
Asynchronously saves the current message as a draft.
saveAsync(callback: (asyncResult: Office.AsyncResult<string>) => void): void;
Parameters
- callback
-
(asyncResult: Office.AsyncResult<string>) => void
When the method completes, the function passed in the callback
parameter is called with a single parameter, asyncResult
, which is an Office.AsyncResult
object. The EWS message ID is returned in the asyncResult.value
property.
Returns
void
Remarks
Minimum permission level: read/write item
Applicable Outlook mode: Message Compose
Important:
In Outlook on the web, new Outlook on Windows, or classic Outlook on Windows in online mode (non-cached mode), the item is saved to the server. In Outlook in cached mode, the item is saved to the local cache.
When working with HTML-formatted content, it's important to note that the Outlook client may modify the content. This means that subsequent calls to methods like
Body.getAsync
,Body.setAsync
, and evensaveAsync
may not result in the same content.The identifier returned is the same as the Exchange Web Services (EWS) item identifier. The item ID returned isn't identical to the Outlook Entry ID or the ID used by the Outlook REST API. Before making REST API calls using this value, it should be converted using
Office.context.mailbox.convertToRestId
.If your add-in calls
saveAsync
to get an item ID to use with EWS or the REST API, be aware that when Outlook is in cached mode, it may take some time before the item is actually synced to the server. Until the item is synced, using the item ID will return an error.In Outlook on the web and new Outlook on Windows, the mailbox account to which a draft is saved varies when
saveAsync
is called on a message that will be sent from a shared mailbox account. If the sender creates a new message from their personal mailbox and selects the shared mailbox account in the From field,saveAsync
saves the draft to the Drafts folder of the user's personal mailbox. If the sender opens the shared mailbox account in a separate browser tab (through the Open another mailbox option, for example) and creates a new message there,saveAsync
saves the draft to the Drafts folder of the shared mailbox.
Errors:
InvalidAttachmentId
: The attachment identifier does not exist.
Examples
Office.context.mailbox.item.saveAsync(
function callback(result) {
// Process the result.
});
// The following is an example of the
// `result` parameter passed to the
// callback function. The `value`
// property contains the item ID of
// the item.
{
"value": "AAMkADI5...AAA=",
"status": "succeeded"
}
setSelectedDataAsync(data, options, callback)
Asynchronously inserts data into the body or subject of a message.
The setSelectedDataAsync
method inserts the specified string at the cursor location in the subject or body of the item, or, if text is selected in the editor, it replaces the selected text. If the cursor is not in the body or subject field, an error is returned. 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 data to be inserted. Data is not to exceed 1,000,000 characters. If more than 1,000,000 characters are passed in, an ArgumentOutOfRange
exception is thrown.
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
: If text, the current style is applied in Outlook on the web, on Windows (new and classic), and on Mac. If the field is an HTML editor, only the text data is inserted, even if the data is HTML. If the data is HTML and the field supports HTML (the subject doesn't), the current style is applied in Outlook on the web and new Outlook on Windows. The default style is applied in Outlook on Windows (classic) and on Mac. If the field is a text field, an InvalidDataFormat
error is returned. If coercionType
is not set, the result depends on the field: if the field is HTML then HTML is used; if the field is text, then plain text is used.
- 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: Message Compose
Errors:
InvalidAttachmentId
: The attachment identifier does not exist.
Examples
Office.context.mailbox.item.setSelectedDataAsync("<b>Hello World!</b>", { coercionType : "html" });
Office.context.mailbox.item.setSelectedDataAsync("Hello World!");
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/90-other-item-apis/set-selected-data.yaml
Office.context.mailbox.item.setSelectedDataAsync("Replaced", function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
console.log("Selected text has been updated successfully.");
} else {
console.error(asyncResult.error);
}
});
setSelectedDataAsync(data, callback)
Asynchronously inserts data into the body or subject of a message.
The setSelectedDataAsync
method inserts the specified string at the cursor location in the subject or body of the item, or, if text is selected in the editor, it replaces the selected text. If the cursor is not in the body or subject field, an error is returned. 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 data to be inserted. Data is not to exceed 1,000,000 characters. If more than 1,000,000 characters are passed in, an ArgumentOutOfRange
exception is thrown.
- 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: Message Compose
Errors:
InvalidAttachmentId
: The attachment identifier does not exist.
Office Add-ins