google-apps-script - 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
任何帮助是极大的赞赏。
解决方案
您可以像这样修改代码:
const getRunAsHtml = (richTextRun) => {
const richText = richTextRun.getText()
.replace(/([\t<>])/g, c => `&#${c.charCodeAt(0)};`)
.replace(/\n/g, '<br>')
// [...]
}
这不仅可以确保在必要时添加换行符,还可以更改特殊字符,例如<
其 HTML 实体代码。您可以通过将特殊字符添加到第一个替换的正则表达式中来使特殊字符列表更长。
推荐阅读
- jquery - 如何在这个对象数组中做一个“for each”?
- vim - vim 命令删除无关字符?
- windows - RDLC 报告的钻取(或向下钻取)功能是否仅适用于 Web 应用程序?
- android-recyclerview - 滑动到回收站查看项目直到显示
- amazon-web-services - Amazon ECS 任务无法连接到 Amazon RDS
- python - 从图像块中生成概率
- python - 通过 shell 调用 python 时出现模块问题
- c# - 抑制特定查询或上下文的实体框架核心查询日志记录
- javascript - 如何将状态传递给 jsx,在状态改变时渲染和更新?
- powershell - 如何使用 xaml 在 Powershell 中对动态编辑的 TextBlock 进行自动换行?