I have been struggling to find a way to send emails through Google Sheet that keep indentations, formatting, line breaks, etc. I know how to do this using HTML in the code, but I am wanting the script to keep the formatting of a cell so that emails can be easily typed and sent out.
I found this code online reached out to the author and no response) that keeps the formatting, but I can't get it to keep the line breaks. https://www.labnol.org/send-rich-text-emails-200830
const sendRichEmail = () => {
const cellAddress = 'A1';
const sheetName = 'Mail Merge';
const recipient = '[email protected]';
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 });
};
I set up a test sheet https://docs.google.com/spreadsheets/d/1C5GS4c_HwFTaMwWFbyLKbfhPRpxnK6BKw2bzAZjgR1U/edit#gid=0
Any help is greatly appreciated.