如何通过客户端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.,
ReadWriteMailboxor at leastReadMailbox) to access email content and attachments. - Fetch Email Metadata: Use
Office.context.mailbox.itemto 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
attachmentscollection, and usegetAsyncto 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
getAsyncwith theEmlcontent 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.
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
WebApplicationInfosettings 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
相关产品推荐
相关产品推荐

