首页 > 解决方案 > Google Script - 通过 Google 表格发送电子邮件,并保留格式、换行符、缩进等

问题描述

我一直在努力寻找一种通过 Google Sheet 发送电子邮件的方法,以保留缩进、格式、换行符等。我知道如何在代码中使用 HTML 来做到这一点,但我希望脚本保持单元格的格式以便可以轻松地输入和发送电子邮件。

我发现此代码在线联系了作者,但没有回应)保持格式,但我无法让它保持换行符。https://www.labnol.org/send-rich-text-emails-200830

const sendRichEmail = () => {
  const cellAddress = 'A1';
  const sheetName = 'Mail Merge';
  const recipient = 'amit@labnol.org';

  const richTextValue = SpreadsheetApp.getActiveSpreadsheet()
    .getSheetByName(sheetName)
    .getRange(cellAddress)
    .getRichTextValue();

  /* Run is a stylized text string used to represent cell text.
     This function transforms the run into HTML with CSS
   */
  const getRunAsHtml = (richTextRun) => {
    const richText = richTextRun.getText();

    // Returns the rendered style of text in a cell.
    const style = richTextRun.getTextStyle();

    // Returns the link URL, or null if there is no link
    // or if there are multiple different links.
    const url = richTextRun.getLinkUrl();

    const styles = {
      color: style.getForegroundColor(),
      'font-family': style.getFontFamily(),
      'font-size': `${style.getFontSize()}pt`,
      'font-weight': style.isBold() ? 'bold' : '',
      'font-style': style.isItalic() ? 'italic' : '',
      'text-decoration': style.isUnderline() ? 'underline' : '',
    };

    // Gets whether or not the cell has strike-through.
    if (style.isStrikethrough()) {
      styles['text-decoration'] = `${styles['text-decoration']} line-through`;
    }

    const css = Object.keys(styles)
      .filter((attr) => styles[attr])
      .map((attr) => [attr, styles[attr]].join(':'))
      .join(';');

    const styledText = `<span style='${css}'>${richText}</span>`;
    return url ? `<a href='${url}'>${styledText}</a>` : styledText;
  };

  /* Returns the Rich Text string split into an array of runs,
  wherein each run is the longest possible
  substring having a consistent text style. */
  const runs = richTextValue.getRuns();

  const htmlBody = runs.map((run) => getRunAsHtml(run)).join('');

  MailApp.sendEmail(recipient, 'Rich HTML Email', '', { htmlBody });
};

我设置了一张测试表https://docs.google.com/spreadsheets/d/1C5GS4c_HwFTaMwWFbyLKbfhPRpxnK6BKw2bzAZjgR1U/edit#gid=0

任何帮助是极大的赞赏。

标签: google-apps-scriptgoogle-sheets

解决方案


您可以像这样修改代码:

const getRunAsHtml = (richTextRun) => {
  const richText = richTextRun.getText()
    .replace(/([\t<>])/g, c => `&#${c.charCodeAt(0)};`)
    .replace(/\n/g, '<br>')
  
  // [...]
}

这不仅可以确保在必要时添加换行符,还可以更改特殊字符,例如<其 HTML 实体代码。您可以通过将特殊字符添加到第一个替换的正则表达式中来使特殊字符列表更长。


推荐阅读