|
| 1 | +/** |
| 2 | + * Rich Text to Email |
| 3 | + * ======================== |
| 4 | + * |
| 5 | + * Written by Amit Agarwal |
| 6 | + * Email: amit@labnol.org |
| 7 | + * Web: https://www.labnol.org |
| 8 | + * Twitter: @labnol |
| 9 | + * |
| 10 | + * Under MIT License |
| 11 | + */ |
| 12 | + |
| 13 | +const sendRichEmail = () => { |
| 14 | + const cellAddress = "A1"; |
| 15 | + const sheetName = "Mail Merge"; |
| 16 | + const recipient = "amit@labnol.org"; |
| 17 | + |
| 18 | + const richTextValue = SpreadsheetApp.getActiveSpreadsheet() |
| 19 | + .getSheetByName(sheetName) |
| 20 | + .getRange(cellAddress) |
| 21 | + .getRichTextValue(); |
| 22 | + |
| 23 | + /* Run is a stylized text string used to represent cell text. |
| 24 | + This function transforms the run into HTML with CSS |
| 25 | + */ |
| 26 | + const getRunAsHtml = (richTextRun) => { |
| 27 | + const richText = richTextRun.getText(); |
| 28 | + |
| 29 | + // Returns the rendered style of text in a cell. |
| 30 | + const style = richTextRun.getTextStyle(); |
| 31 | + |
| 32 | + // Returns the link URL, or null if there is no link |
| 33 | + // or if there are multiple different links. |
| 34 | + const url = richTextRun.getLinkUrl(); |
| 35 | + |
| 36 | + const styles = { |
| 37 | + color: style.getForegroundColor(), |
| 38 | + "font-family": style.getFontFamily(), |
| 39 | + "font-size": `${style.getFontSize()}pt`, |
| 40 | + "font-weight": style.isBold() ? "bold" : "", |
| 41 | + "font-style": style.isItalic() ? "italic" : "", |
| 42 | + "text-decoration": style.isUnderline() ? "underline" : "", |
| 43 | + }; |
| 44 | + |
| 45 | + // Gets whether or not the cell has strikethrough. |
| 46 | + if (style.isStrikethrough()) { |
| 47 | + styles["text-decoration"] = `${styles["text-decoration"]} line-through`; |
| 48 | + } |
| 49 | + |
| 50 | + const css = Object.keys(styles) |
| 51 | + .filter((attr) => styles[attr]) |
| 52 | + .map((attr) => [attr, styles[attr]].join(":")) |
| 53 | + .join(";"); |
| 54 | + |
| 55 | + const styledText = `<span style='${css}'>${richText}</span>`; |
| 56 | + return url ? `<a href='${url}'>${styledText}</a>` : styledText; |
| 57 | + }; |
| 58 | + |
| 59 | + /* Returns the Rich Text string split into an array of runs, |
| 60 | + wherein each run is the longest possible |
| 61 | + substring having a consistent text style. */ |
| 62 | + const runs = richTextValue.getRuns(); |
| 63 | + const htmlBody = runs.map((run) => getRunAsHtml(run)).join(""); |
| 64 | + |
| 65 | + MailApp.sendEmail(recipient, "Rich HTML Email", "", { htmlBody }); |
| 66 | +}; |
0 commit comments