I’m working on a Google Apps Script project and need help with something. I want to grab specific text from a Google Document and use it as email content. Here’s what I’m trying to achieve:
function sendRandomMessage() {
var recipient = "[email protected]";
var emailSubject = "Daily Message";
var messageContent = // need to get this from document
GmailApp.sendEmail(recipient, emailSubject, messageContent);
}
My goal is to randomly select one line from a document that contains numbered items like:
Good morning
Have a great day
Hope you’re doing well
Enjoy your weekend
I want to generate a random number between 1-4, then extract the corresponding line from the document to use as the email body. So if the random number is 2, the email would contain “Have a great day”.
Is there a way to access document content and retrieve specific lines based on their position? I’m familiar with JavaScript but new to Google Apps Script APIs.
I dealt with this exact thing recently. You’ll need to do some string manipulation to parse numbered lists. First, grab the document content with DocumentApp.openById(), then extract the text from each numbered line. When you split by line breaks, you’ll get lines with numbers and periods included. Use regex or substring methods to strip out the numbering format - like if you have “2. Have a great day”, you need to remove "2. " to get clean content for your email. Don’t forget to trim whitespace from each line before filtering. This worked great for my automated messaging system that pulls from a Google Doc with the same formatting.
Use DocumentApp to pull content from your Google Doc. Open it with DocumentApp.openById(‘your-document-id’), then grab the text using getBody().getText(). Split it into lines with split(‘\n’) and filter out empty ones. Pick a random line with Math.floor(Math.random() * filteredLines.length) for your email body.
hey pete! you can use DocumentApp.openById() to get your doc, then use getText() for the text. just split it by lines and choose one randomly with Math.floor(Math.random()). keep the doc format stable tho, or you might face some issues!