【发布时间】:2021-03-15 13:27:02
【问题描述】:
我一直在努力寻找一种通过 Google 表格发送电子邮件以保留缩进、格式、换行符等的方法。我知道如何在代码中使用 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
非常感谢任何帮助。
【问题讨论】:
-
尝试询问作者。他是顶级用户here
-
上周我给他发了电子邮件。我还没有收到回复
-
试试@Amit Agarwal,你能回答这个人的问题吗?
标签: google-apps-script google-sheets