You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过客户端JS从Outlook加载项获取邮件及附件并上传至SharePoint?

Great question! Let's walk through how to build this Outlook add-in using client-side JavaScript, minimizing server-side code as requested:

1. Access Current Email & Attachments with Office.js

First, you'll rely on the official Office.js library (built into Outlook add-ins) to fetch email data. Here's how to do it:

  • Permissions Setup: Make sure your add-in manifest has the right permissions (e.g., ReadWriteMailbox or at least ReadMailbox) to access email content and attachments.
  • Fetch Email Metadata: Use Office.context.mailbox.item to access core email details like subject, body, or sender:
    const currentEmail = Office.context.mailbox.item;
    console.log("Email Subject:", currentEmail.subject);
    console.log("Sender:", currentEmail.sender.emailAddress);
    
  • Retrieve Attachments: Loop through the attachments collection, and use getAsync to pull file content (returned as an ArrayBuffer):
    currentEmail.attachments.forEach(attachment => {
      if (attachment.attachmentType === Office.MailboxEnums.AttachmentType.File) {
        attachment.getAsync((asyncResult) => {
          if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
            const attachmentBuffer = asyncResult.value;
            // Convert to Blob for upload: const attachmentBlob = new Blob([attachmentBuffer]);
          }
        });
      }
    });
    
2. Export as .eml or .msg Format

Office.js has direct support for .eml, while .msg requires a workaround since it's an Outlook-proprietary format:

  • .eml Export: This is straightforward—use getAsync with the Eml content format to fetch the full MIME-compliant eml string:
    currentEmail.getAsync(Office.MailboxEnums.ItemContentFormat.Eml, (asyncResult) => {
      if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
        const emlContent = asyncResult.value;
        // Convert to Blob for storage/upload:
        const emlBlob = new Blob([emlContent], { type: 'message/rfc822' });
      }
    });
    
  • .msg Export: There's no native Office.js API to get raw .msg content. If you absolutely need .msg, you could look for a pure JavaScript library that generates .msg files from email data (but be cautious about add-in security restrictions for external libraries). For most use cases, .eml is a more portable and easier-to-implement alternative.
3. Upload to SharePoint via Client-Side REST API

You can use SharePoint's REST API directly from your add-in, no server-side code needed, by leveraging the user's existing authentication context:

  • Get Access Token: Use Office.js's SSO capability to fetch a bearer token for SharePoint requests:
    Office.context.auth.getAccessTokenAsync({ allowSignInPrompt: true }, (authResult) => {
      if (authResult.status === Office.AsyncResultStatus.Succeeded) {
        const accessToken = authResult.value;
        uploadToSharePoint(accessToken, emlBlob, currentEmail.subject + ".eml");
      }
    });
    
  • Upload File Function: Call SharePoint's file upload endpoint with the blob content:
    function uploadToSharePoint(token, fileBlob, fileName) {
      const spSiteUrl = "https://your-sharepoint-site-url/_api/web/getfolderbyserverrelativeurl('Documents')/files/add(overwrite=true,url='${encodeURIComponent(fileName)}')";
      
      fetch(spSiteUrl, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json;odata=nometadata'
        },
        body: fileBlob
      })
      .then(res => res.json())
      .then(data => {
        console.log("Upload successful!", data);
        // Show success message to user here
      })
      .catch(err => console.error("Upload failed:", err));
    }
    
  • Permissions Note: Ensure your add-in manifest includes WebApplicationInfo settings for SSO, so users can grant access to your SharePoint site without extra login prompts.
Key Considerations
  • Cross-Client Compatibility: Test your add-in across Outlook Web, desktop, and mobile—some API features may have slight platform differences.
  • Large Files: For big attachments or emails, consider implementing chunked uploads via SharePoint's REST API to avoid timeouts.
  • Security: Stick to Office.js's official APIs and avoid untrusted third-party libraries to keep your add-in compliant with Office store policies.

内容的提问来源于stack exchange,提问作者Paddy P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:10:28