MS Outlook – Messages – Get Messages

Estimated reading: 8 minutes

MS Outlook – Messages – Get Messages

Get Outlook messages for a user. Uses the selected mailbox and returns the available result.

Lists mailbox messages. Use Get Folder Messages to limit the operation to one folder. This action exposes Skip Query but does not return a continuation URL; do not derive pagination by simply adding Top Query to Skip Query.

Action details

PropertyValue
Action labelMS Outlook – Messages – Get Messages
CategoryCloudTools
Apex class and methodGetMSOutlookMessages.getMessages
Input typeGetMSOutlookMessages.GetMSOutlookMessagesInput
Output typeList<List<MSOutlookMessage>>
AuthorizationOAuth Delegated (Authorization Code) or OAuth Application (Client Credentials).
Flow automationUse an application connector configured as the Flow default.
Microsoft Graph operationGET /v1.0/me/messages for Authorization Code Flow; otherwise GET /v1.0/users/{userIdOrPrincipalName}/messages.

Prerequisites and permissions

Configure a CloudTools Connector with Connector Type set to Microsoft 365. Complete Microsoft sign-in for delegated access. For application access, grant application permissions and administrator consent, supply the target mailbox user ID or principal name, and ensure the app can access that mailbox.

For basic metadata, Microsoft lists Mail.ReadBasic for delegated access and Mail.ReadBasic.All for application access. Mail.Read or Mail.ReadWrite also permits reading; use Mail.Read or Mail.ReadWrite when message bodies, previews, or attachments are needed. See the Microsoft operation and permissions reference.

Mailbox selection: Authorization Code Flow uses /me and ignores userIdOrPrincipalName. Supplying another user does not redirect that call. Other authorization types use /users/{userIdOrPrincipalName}; their authentication must be valid for Microsoft Graph. Use Graph resource IDs rather than Salesforce record IDs.

Inputs

The table lists action labels, Apex field names, and data types. Provide one non-null request per invocation. Required text must not be blank.

InputApex fieldTypeRequiredDescription
User Id or Principal NameuserIdOrPrincipalNameStringUnless Authorization Code Flow is enabledUser id or user principal name. Required for application authorization; ignored for Authorization Code Flow.
Filter QueryfilterQueryStringNoOData filter query. Supply the value only, without a prefix such as $select= or a full URL. Microsoft validates query support.
Select QueryselectQueryStringNoOData select query. Supply the value only, without a prefix such as $select= or a full URL. Microsoft validates query support.
Expand QueryexpandQueryStringNoOData expand query. Supply the value only, without a prefix such as $select= or a full URL. Microsoft validates query support.
Order By QueryorderbyQueryStringNoOData orderby query. Supply the value only, without a prefix such as $select= or a full URL. Microsoft validates query support.
Top QuerytopQueryStringNoOData top query. Supply the value only, without a prefix such as $select= or a full URL. Microsoft validates query support.
Skip QueryskipQueryStringNoOData skip query. Supply the value only, without a prefix such as $select= or a full URL. Microsoft validates query support.

The invocable input has no connectorId field. Apex and Flow use CloudTools connector selection; the LWC controller accepts an additional connectorId property to select a record. This action does not resolve replacement tokens in its inputs; resolve dynamic values first. See Using Token Replacements.

For a small metadata page, set Select Query to id,subject,parentFolderId and Top Query to 10. Include id if you plan to use the result in another action. When combining Filter Query and Order By Query, Microsoft requires the ordered properties to appear first in the filter in the same order; an incompatible combination can return InefficientFilter.

Outputs

The invocable method returns List<List<MSOutlookMessage>>: one outer result containing the collection for the first request. Read the inner list in Apex; Flow receives a collection output. An empty lookup produces an empty inner list. The JavaScript wrapper returns a flat array.

The implementation reads only the first response page and does not follow or expose @odata.nextLink. Top Query limits the requested page size; the returned collection is not guaranteed to include every matching item.

OutputApex fieldTypeDescription
IdidStringMessage identifier.
SubjectsubjectStringMessage subject.
Body PreviewbodyPreviewStringMessage body preview.
BodybodyMSOutlookMessageItemBodyMessage body.
FromfromRecipientMSOutlookMessageRecipientFrom recipient.
SendersenderRecipientMSOutlookMessageRecipientSender recipient.
To RecipientstoRecipientsList<MSOutlookMessageRecipient>Recipient collection.
Cc RecipientsccRecipientsList<MSOutlookMessageRecipient>CC recipient collection.
Bcc RecipientsbccRecipientsList<MSOutlookMessageRecipient>BCC recipient collection.
Reply ToreplyToList<MSOutlookMessageRecipient>Reply-to recipient collection.
From AddressfromAddressStringFrom email address.
Sender AddresssenderAddressStringSender email address.
To RecipientstoRecipientsCsvStringComma-separated recipients.
Cc RecipientsccRecipientsCsvStringComma-separated CC recipients.
Bcc RecipientsbccRecipientsCsvStringComma-separated BCC recipients.
Received Date TimereceivedDateTimeStringReceived timestamp.
Sent Date TimesentDateTimeStringSent timestamp.
Created Date TimecreatedDateTimeStringCreated timestamp.
Last Modified Date TimelastModifiedDateTimeStringLast modified timestamp.
Parent Folder IdparentFolderIdStringParent folder identifier.
Internet Message IdinternetMessageIdStringInternet message identifier.
Web LinkwebLinkStringOutlook web link.
Is DraftisDraftBooleanWhether message is draft.
Has AttachmentshasAttachmentsBooleanWhether message has attachments.
ImportanceimportanceStringMessage importance.
Conversation IdconversationIdStringConversation identifier.
Conversation IndexconversationIndexStringConversation index.
Follow Up FlagfollowUpFlagMSOutlookMessageFollowupFlagFollow-up metadata.
AttachmentsattachmentsList<DynamicObject>Message attachments.
ExtensionsextensionsList<DynamicObject>Message extensions.
OData TypeodataTypeStringOData type.
OData ETagodataEtagStringOData etag.
Additional PropertiesadditionalPropertiesList<DynamicObject>Additional data returned by query.

Optional properties depend on the response and any Select or Expand query. Do not treat an absent field as proof of its value. Timestamps represented by String remain text. Nested body and recipient properties follow the Apex message model; content, recipient collections, and attachment expansion are not guaranteed.

In the Apex model, Body exposes content and contentType. Each recipient exposes emailAddress.address and emailAddress.name. Follow Up Flag exposes flagStatus, startDateTime, dueDateTime, and completedDateTime; each date object has dateTime and timeZone. Availability depends on response mapping. Use the top-level id for Graph message operations, rather than internetMessageId or conversationId.

Use in Flow

Add MS Outlook – Messages – Get Messages in Flow Builder. Configure a Microsoft 365 application connector as the default for Flow automations, then populate the inputs above. Delegated connectors are not supported for CloudTools Flow automation. Add a fault path for callout errors. This implementation processes only the first input request; it is not a bulk action.

Use in custom Apex

This subscriber-org example uses the Apptigent namespace. Replace placeholders before use. Run in a context that permits callouts with a configured application connector. For an already-authorized delegated connector, omit the user value.

Apptigent.GetMSOutlookMessages.GetMSOutlookMessagesInput request =
    new Apptigent.GetMSOutlookMessages.GetMSOutlookMessagesInput();
request.userIdOrPrincipalName = 'REPLACE_WITH_MICROSOFT_USER_ID_OR_UPN';

List<List<Apptigent.MSOutlookMessage>> results =
    Apptigent.GetMSOutlookMessages.getMessages(
        new List<Apptigent.GetMSOutlookMessages.GetMSOutlookMessagesInput>{ request }
    );

List<Apptigent.MSOutlookMessage> items = results.isEmpty()
    ? new List<Apptigent.MSOutlookMessage>() : results[0];
System.debug(items.size());

Submit one request per invocation. The example does not implement connector setup, delegated sign-in, or exception handling; those belong in the calling application.

Use in a Lightning Web Component

Use getMSOutlookMessages from msOutlookConnectorLib, through MSOutlookConnectorController. This example uses repository c/ imports for a component in the same namespace. Replace placeholders and complete connector authorization before invoking it.

outlookActionExample.js

import { LightningElement } from 'lwc';
import { getMSOutlookMessages, MSOutlookObjects } from 'c/msOutlookConnectorLib';

export default class OutlookActionExample extends LightningElement {
    connectorId = 'REPLACE_WITH_CONNECTOR_RECORD_ID';
    result = null;
    errorMessage = '';
    isRunning = false;
    completed = false;

    async handleRun() {
        if (this.isRunning) {
            return;
        }
        this.isRunning = true;
        this.errorMessage = '';
        try {
            const request = MSOutlookObjects.inputs.message();
            request.connectorId = this.connectorId;
            request.userIdOrPrincipalName = 'REPLACE_WITH_MICROSOFT_USER_ID_OR_UPN';
            const result = await getMSOutlookMessages(request);
            if (!Array.isArray(result)) {
                throw new Error('No collection result was returned.');
            }
            this.result = result;
            this.completed = true;
        } catch (error) {
            this.errorMessage = error.requiresInteractiveAuthorization
                ? 'Sign in to Microsoft for this connector, then try again.'
                : error.message || 'The Outlook action failed.';
        } finally {
            this.isRunning = false;
        }
    }
}

outlookActionExample.html

<template>
    <lightning-button label="Run action" onclick={handleRun}
        disabled={isRunning}></lightning-button>
    <p role="alert">{errorMessage}</p>
</template>

The library accepts one request object and resolves to a flat array of items; use result.length and iterate the array, without an outer Apex list. The shared factory includes inputs for other actions; only the fields in this page and optional connectorId are used here.

The LWC controller flattens body into bodyContent and bodyContentType, recipients into address and CSV fields including replyToRecipientsCsv, and follow-up metadata into flag status and date fields. Use the JavaScript response shape rather than assuming the nested Apex fields are present. The response also exposes rawJson, which is not an invocable Flow output and may be a serialization of the mapped model.

This example reports authorization errors but does not implement sign-in. For delegated access, use getMSOutlookAuthorizationState, beginMSOutlookAuthorization, and createMSOutlookOAuthMessageHandler. Errors expose message and requiresInteractiveAuthorization.

Error handling and troubleshooting

SymptomWhat to check
Required fields errorPass a nonempty list with a non-null first request. Populate required resource fields and User Id or Principal Name for application authorization.
Authorization is requiredComplete or renew the current user’s delegated Microsoft authorization for the selected connector.
Access deniedCheck the operation permission, consent, connector identity, and mailbox access.
Resource not foundVerify IDs belong to the selected mailbox and refer to the expected resource. Authorization Code Flow ignores the user input.
Query rejectedSupply only supported OData values. Simplify Select, Expand, Filter, and Order By queries and review the Microsoft reference.
Unexpected resultCheck for an empty Apex result, a null JavaScript response, omitted properties, or incomplete pagination. Handle exceptions in the caller.
Share this Doc

MS Outlook – Messages – Get Messages

Or copy link

CONTENTS

Free eBook: The Ultimate Guide to Power Platform Custom Connectors

Antimanual

Ask our AI support assistant your questions about our platform, features, and services.

You are offline
Chatbot avatar
What can I help you with?

Subscribe

×
Cancel