在 Outlook 中获取、设置或添加约会或邮件的收件人

使用 Office JavaScript API 轻松识别和管理邮件或约会的收件人。

在本文中,你将了解如何:

  • 从邮件和约会中获取现有收件人
  • 设置收件人以替换现有收件人
  • 向邮件和约会添加新收件人

了解收件人属性

不同的邮件项目类型支持不同的收件人属性。 下表显示了哪些属性可用于邮件和约会。

邮件项类型 收件人属性
邮件
约会

提示

如果外接程序同时对邮件和约会进行作,我们建议调用 Office.context.mailbox.item.itemType 来帮助识别这两种邮件项目类型。 这样,外接程序就可以访问相应的收件人属性。

试用

浏览交互式示例,了解如何管理邮件项目的收件人。 安装 Outlook 加载项Script Lab,然后试用以下示例代码片段。

  • 获取 (消息读取)
  • 获取并设置为 (消息Compose)
  • 获取抄送 (邮件读取)
  • 获取和设置抄送 (消息Compose)
  • 获取和设置密件抄送 (消息Compose)
  • 获取所需的与会者 (约会与会者)
  • 获取和设置所需的与会者 (约会组织者)
  • 获取可选与会者 (约会与会者)
  • 获取和设置可选与会者 (约会组织者)

若要了解详细信息,请参阅使用 Script Lab 探索 Office JavaScript API

获取收件人

本部分标识在阅读和撰写模式下获取收件人的不同方法。

获取处于阅读模式的收件人

在读取模式下,可以直接从父对象访问收件人,如以下示例所示。

Office.context.mailbox.item.cc;

收件人作为 EmailAddressDetails 对象的数组返回。 然后,可以从收件人的相应 EmailAddressDetails 对象中确定以下信息。

在撰写模式下获取收件人

在撰写模式下,必须调用 getAsync 方法来访问收件人,因为用户和加载项可能同时修改收件人。 当多个进程处理同一项时,这种异步方法可防止冲突并确保数据一致性。

方法 getAsync 需要一个回调函数,该回调函数以 EmailAddressDetails 对象数组的形式接收收件人。 每个对象都包含收件人的显示名称、电子邮件地址和类型。

提示

getAsync由于 该方法是异步的,因此,如果后续作依赖于成功获取收件人,则应将代码组织为仅在异步调用成功完成时在相应的回调函数中运行这些作。

以下示例显示邮件或约会中收件人的电子邮件地址。

let item;

// Confirms that the Office.js library is loaded.
Office.onReady((info) => {
    if (info.host === Office.HostType.Outlook) {
        item = Office.context.mailbox.item;
        getAllRecipients();
    }
});

// Gets the email addresses of all the recipients of the item being composed.
function getAllRecipients() {
    let toRecipients, ccRecipients, bccRecipients;

    // Verify if the mail item is an appointment or message.
    if (item.itemType === Office.MailboxEnums.ItemType.Appointment) {
        toRecipients = item.requiredAttendees;
        ccRecipients = item.optionalAttendees;
    } else {
        toRecipients = item.to;
        ccRecipients = item.cc;
        bccRecipients = item.bcc;
    }

    // Get the recipients from the To or Required field of the item being composed.
    toRecipients.getAsync((asyncResult) => {
        if (asyncResult.status === Office.AsyncResultStatus.Failed) {
            write(asyncResult.error.message);
            return;
        }

        // Display the email addresses of the recipients or attendees.
        write(`Recipients in the To or Required field: ${displayAddresses(asyncResult.value)}`);
    });

    // Get the recipients from the Cc or Optional field of the item being composed.
    ccRecipients.getAsync((asyncResult) => {
        if (asyncResult.status === Office.AsyncResultStatus.Failed) {
            write(asyncResult.error.message);
            return;
        }

        // Display the email addresses of the recipients or attendees.
        write(`Recipients in the Cc or Optional field: ${displayAddresses(asyncResult.value)}`);
    });

    // Get the recipients from the Bcc field of the message being composed, if applicable.
    if (bccRecipients.length > 0) {
        bccRecipients.getAsync((asyncResult) => {
        if (asyncResult.status === Office.AsyncResultStatus.Failed) {
            write(asyncResult.error.message);
            return;
        }

        // Display the email addresses of the recipients.
        write(`Recipients in the Bcc field: ${displayAddresses(asyncResult.value)}`);
        });
    } else {
        write("Recipients in the Bcc field: None");
    }
}

// Displays the email address of each recipient.
function displayAddresses (recipients) {
    for (let i = 0; i < recipients.length; i++) {
        write(recipients[i].emailAddress);
    }
}

// Writes to a div with id="message" on the page.
function write(message) {
    document.getElementById("message").innerText += message;
}

提示

若要了解有关异步调用的详细信息,请参阅 Office 外接程序中的异步编程

已解决的收件人

方法 getAsync 仅返回由 Outlook 客户端解析的收件人。 已解析的收件人具有以下特征。

  • 如果收件人的通讯簿中具有已保存的条目,Outlook 会将电子邮件地址解析为收件人保存的显示名称。
  • Teams 会议状态图标显示在收件人的姓名或电子邮件地址之前。
  • 收件人姓名或电子邮件地址后会显示分号。
  • 收件人的姓名或电子邮件地址带有下划线或括在框中。

若要在将电子邮件地址添加到邮件项目后对其进行解析,发件人必须使用 Tab 键或从自动完成列表中选择建议的联系人或电子邮件地址。

在 Outlook 网页版 和 Windows (新) 和经典) 中,如果用户通过从联系人或个人资料卡选择联系人的电子邮件地址链接创建新邮件,则必须首先解析电子邮件地址,以便该电子邮件地址可以包含在通话结果getAsync中。

设置收件人

setAsync 方法将所有现有收件人替换为新列表。 在调用中 setAsync ,必须提供一个数组作为参数的输入参数 recipients ,采用以下格式。

  • SMTP 地址字符串的数组。 例如,["user@contoso.com", "team@contoso.com"]
  • 字典数组,每个字典都包含显示名称和电子邮件地址。 例如,[{ displayName: "Megan Bowen", emailAddress: "megan@contoso.com" }]
  • 对象的数组 EmailAddressDetails ,类似于 方法返回的 getAsync 数组。 例如,[{ displayName: "Megan Bowen", emailAddress: "megan@contoso.com", recipientType: Office.MailboxEnums.RecipientType.User }]

注意

在移动设备上的 Outlook 中,请注意以下事项:

  • setAsync 版本 4.2530.0 开始支持 方法。
  • setAsync当用户从邮件底部的回复字段进行答复时,不支持 方法。
let item;

// Confirms that the Office.js library is loaded.
Office.onReady((info) => {
    if (info.host === Office.HostType.Outlook) {
        item = Office.context.mailbox.item;
        setRecipients();
    }
});

// Sets the recipients of the item being composed.
function setRecipients() {
    let toRecipients, ccRecipients, bccRecipients;

    // Verify if the mail item is an appointment or message.
    if (item.itemType === Office.MailboxEnums.ItemType.Appointment) {
        toRecipients = item.requiredAttendees;
        ccRecipients = item.optionalAttendees;
    } else {
        toRecipients = item.to;
        ccRecipients = item.cc;
        bccRecipients = item.bcc;
    }

    // Set the recipients in the To or Required field of the item being composed.
    toRecipients.setAsync(
        [{
            "displayName": "Graham Durkin", 
            "emailAddress": "graham@contoso.com"
         },
         {
            "displayName": "Donnie Weinberg",
            "emailAddress": "donnie@contoso.com"
         }],
        (asyncResult) => {
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                console.log(asyncResult.error.message);
                return;
            }

            console.log("Successfully set the recipients in the To or Required field.");
            // Run additional operations appropriate to your scenario.
    });

    // Set the recipients in the Cc or Optional field of the item being composed.
    ccRecipients.setAsync(
        [{
            "displayName": "Perry Horning", 
            "emailAddress": "perry@contoso.com"
         },
         {
            "displayName": "Guy Montenegro",
            "emailAddress": "guy@contoso.com"
         }],
        (asyncResult) => {
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                console.log(asyncResult.error.message);
                return;
            }

            console.log("Successfully set the recipients in the Cc or Optional field.");
            // Run additional operations appropriate to your scenario.
    });

    // Set the recipients in the Bcc field of the message being composed.
    if (bccRecipients) {
        bccRecipients.setAsync(
            [{
                "displayName": "Lewis Cate", 
                "emailAddress": "lewis@contoso.com"
            },
            {
                "displayName": "Francisco Stitt",
                "emailAddress": "francisco@contoso.com"
            }],
            (asyncResult) => {
                if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                    console.log(asyncResult.error.message);
                    return;
                }
    
                console.log("Successfully set the recipients in the Bcc field.");
                // Run additional operations appropriate to your scenario.
        });
    }
}

添加收件人

如果不想覆盖约会或邮件中的任何现有收件人,请调用 addAsync 方法。 与 setAsync 方法类似, addAsync 该方法还需要输入 recipients 参数。 可以选择使用 参数为回调提供回调 asyncContext 函数和任何参数。

注意

在移动设备上的 Outlook 中,请注意以下事项:

  • addAsync 版本 4.2530.0 开始支持 方法。
  • addAsync当用户从邮件底部的回复字段进行答复时,不支持 方法。

以下示例检查正在撰写的项目是否为约会,然后向其追加两个必需的与会者。

let item;

// Confirms that the Office.js library is loaded.
Office.onReady((info) => {
    if (info.host === Office.HostType.Outlook) {
        item = Office.context.mailbox.item;
        addAttendees();
    }
});

// Adds the specified recipients as required attendees of the appointment.
function addAttendees() {
    if (item.itemType === Office.MailboxEnums.ItemType.Appointment) {
        item.requiredAttendees.addAsync(
        [{
            "displayName": "Kristie Jensen",
            "emailAddress": "kristie@contoso.com"
         },
         {
            "displayName": "Pansy Valenzuela",
            "emailAddress": "pansy@contoso.com"
          }],
        (asyncResult) => {
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                console.log(asyncResult.error.message);
                return;
            }

            console.log("Successfully added the required attendees.");
            // Run additional operations appropriate to your scenario.
        });
    }
}

另请参阅