messages API
The messages API allows to access and manage the user’s messages.
Note
When the term messageId is used in these documents, it doesn’t refer to the Message-ID email header. It is an internal tracking number that does not remain after a restart. Nor does it follow an email that has been moved to a different folder.
Warning
Some functions in this API potentially return a lot of messages. See Working with message lists for more information.
Permissions
The following permissions influence the behavior of the API. Depending on which permissions are requested, additional methods might be available, or certain data may be included in responses.
Hint
Request permissions only when needed. Unnecessary requests may result in rejection during ATN review.
accountsRead
See your mail accounts, their identities and their folders.
messagesDelete
Permanently delete your email messages.
messagesImport
Import messages into Thunderbird.
messagesModifyPermanent
Permanently modify the source of your messages (including headers, body and attachments).
messagesMove
Copy or move your email messages (including moving them to the trash folder).
messagesRead
Read your email messages.
messagesTags
Create, modify and delete message tags.
messagesUpdate
Change properties and tags of your email messages.
Functions
abortList(messageListId)
– [Added in TB 120]
Finalizes the specified list and terminates any process currently still adding messages.
Required permissions
archive(messageIds)
– [Added in TB 68]
Archives messages using the current settings. Archiving external messages will throw an ExtensionError.
Required permissions
continueList(messageListId)
– [Added in TB 66]
Returns the next chunk of messages in a list. See Working with message lists for more information.
Required permissions
copy(messageIds, destination, [options])
– [Added in TB 66]
Copies messages to a specified folder.
Parameters
messageIds
destination
The folder to copy the messages to.
options
Required permissions
createTag(key, tag, color)
– [Added in TB 102]
Creates a new message tag. Tagging a message will store the tag’s key in the user’s message. Throws if the specified tag key is used already.
Parameters
key
Unique tag identifier (will be converted to lower case). Must not include ()<>{/%*” or spaces.
tag
Human-readable tag name.
color
Tag color in hex format (i.e.: #000080 for navy blue).
Required permissions
delete(messageIds, [options])
– [Added in TB 66]
Deletes messages permanently, or moves them to the trash folder (honoring the account’s deletion behavior settings). Deleting external messages will throw an ExtensionError. The deletePermanently parameter allows immediate permanent deletion, bypassing the trash folder.
Parameters
messageIds
options
deletePermanently
Whether the message will be deleted permanently, regardless of the account’s deletion behavior settings. A permanently deleted message cannot be restored, even if the action is defined as a user action. Use this with care!
isUserAction
Whether this copy operation should be treated as a user action, for example allowing undo.
Required permissions
deleteAttachments(messageId, partNames)
– [Added in TB 123]
Deletes the specified attachments and replaces them by placeholder text attachments with meta information about the original attachments and a text/x-moz-deleted content type. This permanently modifies the message.
Parameters
messageId
partNames
An array of attachments, identifying the to be deleted attachments by their partName.
Required permissions
deleteTag(key)
– [Added in TB 102]
Deletes a message tag, removing it from the list of known tags. Its key will not be removed from tagged messages, but they will appear untagged. Recreating a deleted tag, will make all former tagged messages appear tagged again.
Parameters
key
Unique tag identifier (will be converted to lower case). Must not include ()<>{/%*” or spaces.
Required permissions
get(messageId)
– [Added in TB 66]
Returns the specified message.
Required permissions
getAttachmentFile(messageId, partName)
– [Added in TB 88]
Gets the content of a MessageAttachment as a File object.
The most simple way to get the content of an attachment is to use the text() method of the returned File object:
let attachments = await browser.messages.listAttachments(messageId);
for (let att of attachments) {
let file = await browser.messages.getAttachmentFile(messageId, att.partName);
let content = await file.text();
}
Required permissions
getFull(messageId, [options])
– [Added in TB 66]
Returns the specified message, including all headers and MIME parts. Throws if the message could not be read, for example due to network issues.
Parameters
messageId
options
decodeContent
Whether to decode quoted-printable or base64 encoded content of message parts. Defaults to true.
decodeHeaders
Whether to decode RFC 2047 encoded headers of message parts. Defaults to true.
decrypt
Whether the message should be decrypted. If the message could not be decrypted, its parts are omitted. Defaults to true.
Required permissions
getRaw(message, [options])
– [Added in TB 72]
Returns the raw content of a message. Throws if the message could not be read, for example due to network issues.
Parameters
message
Either a MessageId of an existing message, or a MessagePart with raw header and raw content data representing a full RFC 822 message (the provided data will be used as-is without applying any further encoding). See the decodeHeaders and decodeContent options of getFull(messageId, [options]) for further details on how to retrieve a MessagePart with raw values. You can use decodeMimeHeader(headerName, headerValue, [isMailBoxHeader]) and encodeMimeHeader(headerName, headerValue, [isMailBoxHeader]) to manipulate a raw MessagePart.
options
data_format
The message can either be returned as a DOM File or as a binary string. The historic default is to return a binary string (kept for backward compatibility). However, it is now recommended to use the File format, because the DOM File object can be used as-is with the downloads API and has useful methods to access the content, like File.text() and File.arrayBuffer().
Working with binary strings is error prone and needs special handling:
/**
* Decodes a binary string using the given encoding format and returns a
* JavaScript string. Produces mangled output if used with anything but a binary
* input string.
*/
function decodeBinaryString(binaryString, inputEncoding = "utf-8") {
const buffer = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
buffer[i] = binaryString.charCodeAt(i) & 0xff;
}
const decoder = new TextDecoder(inputEncoding);
return decoder.decode(buffer);
}
See MDN for `supported input encodings <https://developer.mozilla.org/en-US/docs/Web/API/Encoding_API/Encodings>`__.
Supported values:
BinaryString
File
decrypt
Whether the message should be decrypted. Throws, if the message could not be decrypted.
Required permissions
import(file, destination, [properties])
– [Added in TB 106]
Imports a message into a folder. Supports local folders, POP and IMAP folders. Throws, if the destination folder already contains a message with the Message-ID of the message being imported.
Parameters
file
destination
The folder to import the messages into.
properties
Required permissions
list(folder)
– [Added in TB 66]
Gets all messages in a folder.
Required permissions
listAttachments(messageId)
– [Added in TB 88]
Lists the attachments of a message.
Required permissions
listInlineTextParts(messageId)
– [Added in TB 128]
Lists all inline text parts of a message. These parts are not returned by listAttachments(messageId) and usually make up the readable content of the message, mostly with content type text/plain or text/html. If a message only includes a part with content type text/html, the method convertToPlainText(body, [options]) can be used to retreive a plain text version.
Note
A message usually contains only one inline text part per subtype, but technically messages can contain multiple inline text parts per subtype.
Required permissions
Returns a list of tags that can be set on messages, and their human-friendly name, colour, and sort order.
Required permissions
move(messageIds, destination, [options])
– [Added in TB 66]
Moves messages to a specified folder. If the messages cannot be removed from the source folder, they will be copied instead of moved. Moving external messages will throw an ExtensionError.
Parameters
messageIds
destination
The folder to move the messages to.
options
Required permissions
openAttachment(messageId, partName, tabId)
– [Added in TB 114]
Opens the specified attachment.
Parameters
messageId
partName
tabId
The ID of the tab associated with the message opening.
Required permissions
query([queryInfo])
– [Added in TB 69]
Gets all messages that have the specified properties, or all messages if no properties are specified. Messages of unified mailbox folders are not included by default (as that could double the amount of returned messages), but explicitly specifying a unified mailbox folder is supported.
Parameters
queryInfo
accountId
Limits the search to the specified account(s). Accounts are searched in the specified order.
attachment
Whether the message has attachments, or not. Supports to specify a QueryRange (min/max) instead of a simple boolean value (none/some).
author
Returns only messages with this value matching the author. The search value is a single email address, a name or a combination (e.g.: Name <user@domain.org>). The address part of the search value (if provided) must match the author’s address completely. The name part of the search value (if provided) must match the author’s name partially. All matches are done case-insensitive.
autoPaginationTimeout
Set the timeout in ms after which results should be returned, even if the nominal number of messages-per-page has not yet been reached. Defaults to 1000 ms. Setting it to 0 will disable auto-pagination.
body
Returns only messages with this value in the body of the mail.
flagged
Returns only flagged (or unflagged if false) messages.
folder
Returns only messages from the specified folder. The
permission is required.folderId
Limits the search to the specified folder(s). Folders are searched in the specified order. The
permission is required.fromDate
fromMe
Returns only messages with the author’s address matching any configured identity.
fullText
Returns only messages with this value somewhere in the mail (subject, body or author).
headerMessageId
Returns only messages with a Message-ID header matching this value.
includeSubFolders
Search the specified folder recursively.
junk
Returns only messages whith the specified junk state.
junkScore
Returns only messages with a junk score in the specified range.
messagesPerPage
Set the nominal number of messages-per-page for this query. Defaults to 100 messages.
new
Returns only messages with the specified new state.
online
Query the server directly instead of the local message database. Online queries currently only support querying the headerMessageId property. Currently only supported for NNTP accounts.
recipients
Returns only messages whose recipients match all specified addresses. The search value is a semicolon separated list of email addresses, names or combinations (e.g.: Name <user@domain.org>). For a match, all specified addresses must equal a recipient’s address completely and all specified names must match a recipient’s name partially. All matches are done case-insensitive.
returnMessageListId
The messageListId is usually returned together with the first page, after some messages have been found. Enabling this option will change the return value of this function and return the messageListId directly.
size
Returns only messages with a size in the specified byte range.
subject
Returns only messages whose subject contains the provided string.
tags
Returns only messages with the specified tags. For a list of available tags, call the list() method.
toDate
toMe
Returns only messages with at least one recipient address matching any configured identity.
unread
Returns only unread (or read if false) messages.
Required permissions
update(messageId, newProperties)
– [Added in TB 66]
Updates message properties and tags. Updating external messages will throw an ExtensionError.
Required permissions
updateTag(key, updateProperties)
– [Added in TB 102]
Updates a message tag. Throws if the specified tag key does not exist.
Parameters
key
Unique tag identifier (will be converted to lower case). Must not include ()<>{/%*” or spaces.
updateProperties
Required permissions
Events
onCopied
– [Added in TB 91]
Fired when messages have been copied.
Parameters for onCopied.addListener(listener)
listener(originalMessages, copiedMessages)
A function that will be called when this event occurs.
Parameters passed to the listener function
originalMessages
copiedMessages
Required permissions
onDeleted
– [Added in TB 91]
Fired when messages have been permanently deleted.
Parameters for onDeleted.addListener(listener)
listener(messages)
A function that will be called when this event occurs.
Required permissions
onMoved
– [Added in TB 91]
Fired when messages have been moved.
Parameters for onMoved.addListener(listener)
listener(originalMessages, movedMessages)
A function that will be called when this event occurs.
Parameters passed to the listener function
originalMessages
movedMessages
Required permissions
onNewMailReceived
– [Added in TB 75]
Fired when a new message is received, and has been handled by message filters and junk classification. Filters running after junk classification may move the message again.
Parameters for onNewMailReceived.addListener(listener, monitorAllFolders)
listener(folder, messages)
A function that will be called when this event occurs.
monitorAllFolders
Monitor all folders (including all special use folders as defined by MailFolderSpecialUse) instead of just inbox folders and normal folders.
Parameters passed to the listener function
folder
messages
Required permissions
onUpdated
– [Added in TB 91]
Fired when one or more properties of a message have been updated.
Parameters for onUpdated.addListener(listener)
listener(message, changedProperties, oldProperties)
A function that will be called when this event occurs.
Parameters passed to the listener function
message
changedProperties
oldProperties
Required permissions
Types
InlineTextPart
– [Added in TB 128]
An inline part with content type text/*. These parts are not returned by listAttachments(messageId) and usually make up the readable content of the message, mostly with content type text/plain or text/html
object
content
The content of this inline text part.
contentType
The content type of the part. Most common types for inline text parts are text/plain and text/html. Possible other (deprecated) types are text/richtext and text/enriched. Some calendaring services include an inline text part with type text/calendar.
MailBoxHeaderString
– [Added in TB 131]
Content may either be a single email address, or a mailbox string (see RFC 5322, section 3.4). Use parseMailboxString(mailboxString, [preserveGroups]) to extract the name and/or the email from the mailbox string.
string
MessageAttachment
– [Added in TB 98]
Represents an attachment in a message.
object
contentDisposition
The content disposition of the attachment, for example attachment for normal attachments, or inline for inline attachments.
contentType
The content type of the attachment. A value of text/x-moz-deleted indicates that the original attachment was permanently deleted and replaced by a placeholder text attachment with some meta information about the original attachment.
headers
A dictionary object of RFC 2047 decoded attachment headers as key-value pairs, with the header name as key, and an array of headers as value.
name
The name, as displayed to the user, of this attachment. This is usually but not always the filename of the attached file.
partName
Identifies the MIME part of the message associated with this attachment.
size
The size in bytes of this attachment.
contentId
The content-id of this part. Available for related parts, which are referenced from other places inside the same message (e.g. inline images).
message
A MessageHeader, if this attachment is a message.
MessageHeader
– [Added in TB 89]
Basic information about a message.
object
author
bccList
The Bcc recipients. Not populated for news/nntp messages.
ccList
The Cc recipients. Not populated for news/nntp messages.
date
external
Whether this message is a real message or an external message (opened from a file or from an attachment).
flagged
Whether this message is flagged (a.k.a. starred).
headerMessageId
The message-id header of the message.
headersOnly
Some account types (for example pop3) allow to download only the headers of the message, but not its body. The body of such messages will not be available.
id
junk
Whether the message has been marked as junk. Always false for news/nntp messages and external messages.
junkScore
The junk score associated with the message. Always 0 for news/nntp messages and external messages.
new
Whether the message has been received recently and is marked as new.
recipients
The To recipients. Not populated for news/nntp messages.
size
The total size of the message in bytes.
subject
The subject of the message.
tags
Tags associated with this message. For a list of available tags, use list().
folder
The
permission is required for this property to be included. Not available for external or attached messages.read
Whether the message has been marked as read. Not available for external or attached messages.
MessageId
– [Added in TB 122]
A unique id representing a MessageHeader and the associated message. This id doesn’t refer to the Message-ID email header. It is an internal tracking number that does not remain after a restart. Nor does it follow an email that has been moved to a different folder.
integer
MessageList
– [Added in TB 89]
See Working with message lists for more information.
object
id
Id of the message list, to be used with continueList(messageListId) or abortList(messageListId).
messages
MessagePart
– [Added in TB 89]
Represents an email message “part”, which could be the whole message.
object
body
The quoted-printable or base64 decoded content of the part. Only present for parts with a content type of text/* and only if requested, see the decodeContent option of getFull(messageId, [options]). Use getAttachmentFile(messageId, partName) to retrieve the content of parts which have a content type other than text/*.
contentType
decryptionStatus
headers
A dictionary object of RFC 2047 decoded part headers as key-value pairs, with the header name as key, and an array of headers as value. Only present if requested, see the decodeHeaders option of getFull(messageId, [options]).
name
Name of the part, if it is a file.
partName
The identifier of this part, used in getAttachmentFile(messageId, partName).
parts
Any sub-parts of this part.
rawBody
The raw content of the part. Only present if requested, see the decodeContent option of getFull(messageId, [options]).
rawHeaders
A dictionary object of raw part headers as key-value pairs, with the header name as key, and an array of headers as value. Only present if requested, see the decodeHeaders option of getFull(messageId, [options]).
size
The size of this part. The size of parts with content type message/rfc822 is not the actual message size (on disc), but the total size of its decoded body parts, excluding headers.
MessageProperties
– [Added in TB 106]
Message properties used in update(messageId, newProperties) and import(file, destination, [properties]). They can also be monitored by onUpdated.
object
flagged
Whether the message is flagged (a.k.a starred).
junk
Whether the message is marked as junk. Only supported in update(messageId, newProperties).
new
Whether the message is marked as new. Only supported in import(file, destination, [properties]).
read
Whether the message is marked as read.
tags
QueryRange
– [Added in TB 121]
An object defining a range.