|
| 1 | +--- |
| 2 | +title: Save and email as a PDF |
| 3 | +description: Use Office Scripts to save a worksheet as a PDF and then email that PDF. |
| 4 | +ms.date: 07/03/2025 |
| 5 | +ms.localizationpriority: medium |
| 6 | +--- |
| 7 | + |
| 8 | +# Save a worksheet and email it as a PDF (preview) |
| 9 | + |
| 10 | +Use Office Scripts to save a worksheet as a PDF and email it to yourself or your team. |
| 11 | + |
| 12 | +> [!NOTE] |
| 13 | +> The script in this sample is provided as a preview for developers and may change based on feedback that we receive. Do not use this script in a production environment. |
| 14 | +
|
| 15 | +## Solution |
| 16 | + |
| 17 | +1. Create a new Excel file in your OneDrive. |
| 18 | +1. Add data to your workbook. |
| 19 | +1. Create the script from this sample. |
| 20 | +1. Replace `[email protected]` in this sample with your desired recipient email address. |
| 21 | +1. Adjust the `subject` and `content` values. |
| 22 | +1. Run the script. |
| 23 | + |
| 24 | +## Sample code: Save as a PDF and send via email |
| 25 | + |
| 26 | +```TypeScript |
| 27 | +/** |
| 28 | + * This script saves a worksheet as a PDF, downloads that PDF to your computer, and emails the PDF to a recipient. |
| 29 | + */ |
| 30 | +function main(workbook: ExcelScript.Workbook) { |
| 31 | + // Create the PDF. |
| 32 | + const pdfObject = OfficeScript.convertToPdf(); |
| 33 | + const pdfFile = { name: "report.pdf", content: pdfObject }; // Enter your desired PDF name here. |
| 34 | + |
| 35 | + // Download the PDF. |
| 36 | + OfficeScript.downloadFile(pdfFile); // Not required. Remove this line if you don't want to download the PDF. |
| 37 | + |
| 38 | + // Email the PDF. |
| 39 | + OfficeScript.sendMail({ |
| 40 | + to: "[email protected]", // Enter your recipient email address here. |
| 41 | + subject: "[Demo] Monthly Sales Report", // This is the subject of your email. |
| 42 | + content: "Here's the Monthly Sales Report", // This is the content within your email. |
| 43 | + attachments: [pdfFile] |
| 44 | + }) |
| 45 | +} |
| 46 | +``` |
| 47 | + |
| 48 | +> [!TIP] |
| 49 | +> Use the properties of the [MailProperties](/javascript/api/office-scripts/excelscript/global.officescript.mailproperties) interface to add more details to your email, such as `cc`, `bcc`, and `importance` values. |
| 50 | +
|
| 51 | +## Troubleshooting |
| 52 | + |
| 53 | +### Error: Protected document |
| 54 | + |
| 55 | +The [sensitivity label](https://support.microsoft.com/office/2f96e7cd-d5a4-403b-8bd7-4cc636bae0f9) for your workbook is preventing the script from sending an email. To resolve this error, change the sensitivity label of your workbook to General, Public, or Non-Business. Reload the workbook, and then run the script again. |
0 commit comments