在 Outlook 中管理撰写窗体中的项目附件

Office JavaScript API 提供了多个 API,可用于在用户撰写时管理项目的附件。

附加文件或 Outlook 项目

可以使用适合附件类型的方法将文件或 Outlook 项目附加到撰写窗体。

这些是异步方法,这意味着无需等待操作完成即可继续执行。 根据要添加的附件的原始位置和大小,异步调用可能需要一段时间才能完成。

如果某些任务依赖于要完成的操作,则应在回调函数中执行这些任务。 此回调函数是可选的,在附件上传完成后调用。 回调函数采用 AsyncResult 对象作为输出参数,该参数提供添加附件的任何状态、错误和返回值。 如果此回调需要任何额外参数,则可以在可选的 options.asyncContext 参数中指定它们。 options.asyncContext 可以是回调函数预期的任意类型。

例如,可以将 定义为 options.asyncContext 包含一个或多个键值对的 JSON 对象。 有关将可选参数传递给异步方法的更多示例,请参阅 Office 外接程序的 异步编程平台。以下示例演示如何使用 asyncContext 参数将两个参数传递给回调函数。

const options = { asyncContext: { var1: 1, var2: 2 } };

Office.context.mailbox.item.addFileAttachmentAsync('https://contoso.com/rtm/icon.png', 'icon.png', options, callback);

可以使用 对象的 和 error 属性AsyncResult检查回调函数status中异步方法调用的成功或错误。 如果附加成功完成,则可以使用 AsyncResult.value 属性获取附件 ID。 附件 ID 是一个证书,您稍后可使用附件 ID 删除附件。

注意

附件 ID 仅在同一会话中有效,不保证跨会话映射到同一附件。 会话结束的示例包括当用户关闭加载项时,或者用户开始在内联窗体中撰写,然后弹出内联窗体以在单独的窗口中继续。

提示

可以附加到邮件项目的文件或 Outlook 项目有限制,例如附件数量及其大小。 有关进一步的指导,请参阅 JavaScript API 的限制

附加文件

可以使用 方法并指定文件的 URI,在撰写窗体 addFileAttachmentAsync 中将文件附加到邮件或约会。 还可以使用 addFileAttachmentFromBase64Async 方法,将 Base64 编码的字符串指定为输入。 如果文件受保护,您可以包括相应的标识或身份验证令牌作为 URI 查询字符串参数。 Exchange 将向 URI 发出调用以获取附件,保护文件的 Web 服务将需要使用令牌作为进行身份验证的一种方式。

下面的 JavaScript 示例是从 Web 服务器将文件、picture.png 附加到正在撰写的邮件或约会的撰写加载项。 回调函数采用 asyncResult 作为参数,检查结果状态,并在方法成功时获取附件 ID。

Office.initialize = function () {
    // Checks for the DOM to load using the jQuery ready method.
    $(document).ready(function () {
        // After the DOM is loaded, app-specific code can run.
        // Add the specified file attachment to the item
        // being composed.
        // When the attachment finishes uploading, the
        // callback function is invoked and gets the attachment ID.
        // You can optionally pass any object that you would
        // access in the callback function as an argument to
        // the asyncContext parameter.
        Office.context.mailbox.item.addFileAttachmentAsync(
            `https://webserver/picture.png`,
            'picture.png',
            { asyncContext: null },
            function (asyncResult) {
                if (asyncResult.status === Office.AsyncResultStatus.Failed){
                    write(asyncResult.error.message);
                } else {
                    // Get the ID of the attached file.
                    const attachmentID = asyncResult.value;
                    write('ID of added attachment: ' + attachmentID);
                }
            });
    });
}

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

若要将内联 base64 图像添加到正在撰写的邮件或约会的正文,必须先使用 Office.context.mailbox.item.body.getAsync 方法获取当前项目正文,然后再使用 addFileAttachmentFromBase64Async 方法插入图像。 否则,图像在插入后不会呈现在正文中。 有关指导,请参阅以下 JavaScript 示例,该示例将内联 Base64 图像添加到项正文的开头。

const mailItem = Office.context.mailbox.item;
const base64String =
  "iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAnUExURQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN0S+bUAAAAMdFJOUwAQIDBAUI+fr7/P7yEupu8AAAAJcEhZcwAADsMAAA7DAcdvqGQAAAF8SURBVGhD7dfLdoMwDEVR6Cspzf9/b20QYOthS5Zn0Z2kVdY6O2WULrFYLBaLxd5ur4mDZD14b8ogWS/dtxV+dmx9ysA2QUj9TQRWv5D7HyKwuIW9n0vc8tkpHP0W4BOg3wQ8wtlvA+PC1e8Ao8Ld7wFjQtHvAiNC2e8DdqHqKwCrUPc1gE1AfRVgEXBfB+gF0lcCWoH2tYBOYPpqQCNwfT3QF9i+AegJfN8CtAWhbwJagtS3AbIg9o2AJMh9M5C+SVGBvx6zAfmT0r+Bv8JMwP4kyFPir+cswF5KL3WLv14zAFBCLf56Tw9cparFX4upgaJUtPhrOS1QlY5W+vWTXrGgBFB/b72ev3/0igUdQPppP/nfowfKUUEFcP207y/yxKmgAYQ+PywoAFOfCH3A2MdCFzD3kdADBvq10AGG+pXQBgb7pdAEhvuF0AIc/VtoAK7+JciAs38KIuDugyAC/v4hiMCE/i7IwLRBsh68N2WQjMVisVgs9i5bln8LGScNcCrONQAAAABJRU5ErkJggg==";

// Get the current body of the message or appointment.
mailItem.body.getAsync(Office.CoercionType.Html, (bodyResult) => {
  if (bodyResult.status === Office.AsyncResultStatus.Succeeded) {
    // Insert the Base64 image to the beginning of the body.
    const options = { isInline: true, asyncContext: bodyResult.value };
    mailItem.addFileAttachmentFromBase64Async(base64String, "sample.png", options, (attachResult) => {
      if (attachResult.status === Office.AsyncResultStatus.Succeeded) {
        let body = attachResult.asyncContext;
        body = body.replace("<p class=MsoNormal>", `<p class=MsoNormal><img src="cid:sample.png">`);
        mailItem.body.setAsync(body, { coercionType: Office.CoercionType.Html }, (setResult) => {
          if (setResult.status === Office.AsyncResultStatus.Succeeded) {
            console.log("Inline Base64 image added to the body.");
          } else {
            console.log(setResult.error.message);
          }
        });
      } else {
        console.log(attachResult.error.message);
      }
    });
  } else {
    console.log(bodyResult.error.message);
  }
});

附加 Outlook 项目

可以通过指定项目的 Exchange Web Services (EWS) ID,将 Outlook 项目 ((例如,电子邮件、日历或联系人项目) 附加到撰写窗体中的邮件或 addItemAttachmentAsync 约会)。 可以使用 mailbox.makeEwsRequestAsync 方法并访问 EWS 操作 FindItem,获取用户邮箱中电子邮件、日历、联系人或任务项的 EWS ID。 item.itemId 属性还提供阅读窗体中某个现有项目的 EWS ID。

以下 JavaScript 函数 addItemAttachment扩展了上面的第一个示例,并将项目作为附件添加到正在撰写的电子邮件或约会中。 此函数将要附加的项目的 EWS ID 作为实参。 如果附加成功,它将获取附件 ID 以供进一步处理,包括在同一会话中删除该附件。

// Adds the specified item as an attachment to the composed item.
// ID is the EWS ID of the item to be attached.
function addItemAttachment(itemId) {
    // When the attachment finishes uploading, the
    // callback function is invoked. Here, the callback
    // function uses only asyncResult as a parameter,
    // and if the attaching succeeds, gets the attachment ID.
    // You can optionally pass any other object you wish to
    // access in the callback function as an argument to
    // the asyncContext parameter.
    Office.context.mailbox.item.addItemAttachmentAsync(
        itemId,
        'Welcome email',
        { asyncContext: null },
        function (asyncResult) {
            if (asyncResult.status === Office.AsyncResultStatus.Failed){
                write(asyncResult.error.message);
            } else {
                const attachmentID = asyncResult.value;
                write('ID of added attachment: ' + attachmentID);
            }
        });
}

注意

您可以使用撰写加载项在 Outlook 网页版、移动设备或 Windows (预览版中附加定期约会的实例,) 。 但是,在 Windows 或 Mac 上支持 Outlook 客户端中,尝试附加实例会导致将定期系列附加到父约会 () 。

获取附件

要求集 1.8 中提供了用于在撰写模式下获取附件的 API。

可以使用 getAttachmentsAsync 方法获取正在撰写的邮件或约会的附件。

若要获取附件的内容,可以使用 getAttachmentContentAsync 方法。 AttachmentContentFormat 枚举中列出了支持的格式。

应使用AsyncResult输出参数对象提供回调函数,以检查状态和任何错误。 还可以使用可选 asyncContext 参数将任何其他参数传递给回调函数。

以下 JavaScript 示例获取附件,并允许你为每个受支持的附件格式设置不同的处理。

const item = Office.context.mailbox.item;
const options = {asyncContext: {currentItem: item}};
item.getAttachmentsAsync(options, callback);

function callback(result) {
  if (result.value.length > 0) {
    for (let i = 0 ; i < result.value.length ; i++) {
      result.asyncContext.currentItem.getAttachmentContentAsync(result.value[i].id, handleAttachmentsCallback);
    }
  }
}

function handleAttachmentsCallback(result) {
  // Parse string to be a url, an .eml file, a Base64-encoded string, or an .icalendar file.
  switch (result.value.format) {
    case Office.MailboxEnums.AttachmentContentFormat.Base64:
      // Handle file attachment.
      break;
    case Office.MailboxEnums.AttachmentContentFormat.Eml:
      // Handle email item attachment.
      break;
    case Office.MailboxEnums.AttachmentContentFormat.ICalendar:
      // Handle .icalender attachment.
      break;
    case Office.MailboxEnums.AttachmentContentFormat.Url:
      // Handle cloud attachment.
      break;
    default:
      // Handle attachment formats that are not supported.
  }
}

删除附件

使用 removeAttachmentAsync 方法时,可以通过指定相应的附件 ID,从撰写表单中的邮件或约会项目中删除文件或项目附件。

重要

如果使用要求集 1.7 或更低版本,则只应删除同一个加载项在同一会话中添加的附件。

addFileAttachmentAsyncaddItemAttachmentAsyncgetAttachmentsAsync 方法类似, removeAttachmentAsync 是一种异步方法。 应使用AsyncResult输出参数对象提供回调函数,以检查状态和任何错误。 还可以使用可选 asyncContext 参数将任何其他参数传递给回调函数。

以下 JavaScript 函数 removeAttachment继续扩展上述示例,并从正在撰写的电子邮件或约会中删除指定的附件。 此函数将要删除的附件的 ID 作为实参。 可以在成功 addFileAttachmentAsync调用 、 addFileAttachmentFromBase64AsyncaddItemAttachmentAsync 方法后获取附件的 ID,并在后续 removeAttachmentAsync 方法调用中使用它。 还可以调用 getAttachmentsAsync 要求集 1.8) 中引入 (以获取该外接程序会话的附件及其 ID。

// Removes the specified attachment from the composed item.
function removeAttachment(attachmentId) {
    // When the attachment is removed, the callback function is invoked.
    // Here, the callback function uses an asyncResult parameter and
    // gets the ID of the removed attachment if the removal succeeds.
    // You can optionally pass any object you wish to access in the
    // callback function as an argument to the asyncContext parameter.
    Office.context.mailbox.item.removeAttachmentAsync(
        attachmentId,
        { asyncContext: null },
        function (asyncResult) {
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                write(asyncResult.error.message);
            } else {
                write('Removed attachment with the ID: ' + asyncResult.value);
            }
        });
}

另请参阅