Extracting Email Address & Name From Forwarded Emails - javascript

I'm trying to use Google Script to extract email address and name from forwarded emails that I've filed under a specific label.
The emails look like this:
From: Person A
Sent: Sunday, September 22, 2019 8:00 PM
To: Other, Email
Subject: Forwarded Email
BODY
They have all have been forwarded to this specific inbox. Therefore the headers actually include my other email address I forwarded from.
I've sorted over 2000 emails and now for each of the labels I want to extract the name of the sender (Person A) and their email address (person#gmail.com) in a spreadsheet. Preferably, I can have the first and last name in separate cells (e.g. Person | A | email address)
The code I have thus far is below:
function processInboxToSheet() {
// Have to get data separate to avoid google app script limit!
var start = 0;
var label = GmailApp.getUserLabelByName("LABEL");
var threads = label.getThreads();
var sheet = SpreadsheetApp.getActiveSheet();
var result = [];
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
var content = messages[0].getPlainBody();
// implement your own parsing rule inside
if (content) {
var tmp;
tmp = content.match(/From:\n([A-Za-z0-9\s]+)(\r?\n)/);
var name = (tmp && tmp[1]) ? tmp[1].trim() : 'No name';
tmp = content.match(/<\n([A-Za-z0-9#.]+)/);
var email = (tmp && tmp[1]) ? tmp[1].trim() : 'No email';
sheet.appendRow([name, email]);
Utilities.sleep(500);
}
}
};
I only get No name and No email as output so something is not quite working in the code. I would appreciate your help.

You are parsing the plain body, it doesn’t contain to and from. It only contains the message body. The API has methods getTo() and getFrom() that contains what you want to parse. See the API for GmailMessage for more details.

Related

MailApp.sendEmail sending email to my inbox even my even not set together to get the email

I have an email script that will send out email to all emails that are in the list of a google sheet. But then, when I run the script, it is also sent to my Inbox instead of only to register into my Sent folder. Before this no issue (after being using the same script for a long time, 1+ year), it just happened a few months back.
I've found similar issue from this post but couldn't get the suggestions work, example:
To replace Mailapp.sendEmail with Gmailapp.sendEmail
Checked if I have any wrong filter in my email
Attached the script as below:
function arrayUnique(arr) {
var tmp = [];
// filter out duplicates
return arr.filter(function(item, index){
var stringItem = item.toString(); // convert row arrays to strings for comparison
tmp.push(stringItem); // push string items into temporary arrays
return tmp.indexOf(stringItem) >= index; // only return the first occurrence of the strings
})}
function sendEmail() {
var sheet = SpreadsheetApp.getActive().getSheetByName("pending list")
var sub = "Error Fix Required"
var data = sheet.getRange(3,1, sheet.getLastRow(), 5).getDisplayValues().filter(function (row){
var date = sheet.getRange(1,2).getDisplayValues()
return row[3] == date
})
var filterunique = arrayUnique(data)
var json = {}
filterunique.forEach(function (item){
if(item[2] || item[2].length > 0){
if(!json[item[2]]){
json[item[2]] = []
}
json[item[2]].push(item[0])
}
})
Object.keys(json).forEach(function(to){
var email = "{{user}}#shopee.com"
email = email.replace(/{{user}}/gi,to)
var sku = "<br><ul><li>" + json[to].join("</li><li>") + "</li></ul>"
var body = "Hi " + to +", <br><br>The following require your kind attention:" + sku + "Please go to this <a href='https://docs.google.com/spreadsheets/d/1nMKeW//'>link</a> to rectify your submissions by today 4pm.<br><br> Thanks."
MailApp.sendEmail({
to: email,
subject: sub,
htmlBody: body
});
})
}
Also attached what I received in my Inbox:
Change this:
MailApp.sendEmail({to: email,subject: sub, htmlBody: body});
to this:
GmailApp.sendEmail(emai,sub,'',{htmlBody:body});

Extract subject and body text from Gmail messages and export to CSV

My current project is to take a set of emails from my gmail account and create a book from them, where each letter is a chapter.
I wrote up a Google Script snippet that successfully extracts the subject, date, and body text from all emails under a certain
label and writes them to a Google Document. This is not quite ideal, as I would prefer to ultimately have all this text in
markdown or LaTeX for formatting more carefully, but I was only familiar with how to to write to a Google Doc, based on the
Gmail API.
The fastest way for A to B for me would be to figure out how to alter this code so that it writes the text to a CSV file, containing
subject, date, and body columns. From there, I can process and parse it out into LaTeX and assign the necessary header styles and
formats there instead; however, I don't see much guidance on that file format in the API. Any guidance on how to adapt this script for
that purpose would be very welcome. Thanks.
function collectLetters() {
var fileName = 'OUTPUT_GOOGLE_DOC_FILENAME';
var labelName = 'MY_LABEL';
var timeZoneName = 'GMT'
var dateFormat = "dd | MM | yyyy"
var docBody;
var subject;
var date;
var body;
var message;
var num;
var datePar;
var bodyPar;
var subjectPar;
var numPar;
// get the handle for label
var label = GmailApp.getUserLabelByName(labelName);
var threads = label.getThreads();
// Create a new Google Doc
var doc = DocumentApp.create(fileName);
// get all the threads from label
for (var i = threads.length-1; i >= 0; i--) {
// EXTRACT FROM EMAIL: date, subject and body
message = threads[i].getMessages()[0];
subject = message.getSubject();
date = Utilities.formatDate(message.getDate(), timeZoneName, dateFormat)
body = message.getPlainBody().replace(/\r\n\r\n/gm,'aaaLINEBREAKERaaa').replace(/\r\n/gm,' ').replace(/ /gm,' ')
var splitBody = body.split('aaaLINEBREAKERaaa');
// APPEND TO GOOGLE DOC: Date (as Header)
datePar = doc.getBody().appendParagraph(date);
datePar.setHeading(DocumentApp.ParagraphHeading.HEADING1);
// APPEND TO GOOGLE DOC: Subject (as Subtitle)
if (subject.length > 0) {
subjectPar = doc.getBody().appendParagraph(subject);
}
else{
subjectPar = doc.getBody().appendParagraph("no subject");
}
subjectPar.setHeading(DocumentApp.ParagraphHeading.SUBTITLE);
// APPEND TO GOOGLE DOC: Body (as Normal)
docBody = doc.getBody()
splitBody.forEach(function (paragraphText) {
this.appendParagraph(paragraphText).setHeading(DocumentApp.ParagraphHeading.NORMAL);
}, docBody);
// Start a new page
doc.getBody().appendPageBreak();
//Logger.log(subject);
}
}

Syntax issue involving a ".replace" function

So I have a Google sheet that collects registration data from customers. Included in the data collected is a student's name, the session the student elected to attend and a credit card number. Once a submission has been made, I get a notification. Upon notification, I go to my Google sheet and charge the credit card the appropriate amount.
Once the credit card has been charged, I then want to generate a confirmation email to the customer that includes the student's name, the session the student registered to attend and the amount charged to the credit card. My code seems to work fine except when it comes to replacing curly bracket placeholders in my "template text" (i.e., {Name},{sessions} and {ChargeAmount} with the actual values which I've defined as variables.
Note: When I just replace {StudentName} with text like "Joe" it works. However, {Sessions} does not get replaced and neither does {ChargeAmount}. I think this is a syntax error.
Here's what I really want to happen but can't get to work:
var emailText = templateText.replace("{Name}",studentName);templateText.replace("{Sessions}",sessionName);templateText.replace("{ChargeAmount}",ChgAmt);
function SendEmail() {
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("B2");
var studentRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("C2");
var studentName = studentRange.getValues();
var sessionRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("D2");
var sessionName = sessionRange.getValues();
var emailAddress = emailRange.getValues();
var ChgAmt = Browser.inputBox("Charge Amount");
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1,1).getValue();
// NOTE! What I really want to do is replace {Name} with the var "studentName"... not the text "Joe", {Sessions} with the var "sessionName" and {ChargeAmount} with the var "ChgAmt". I can't this to work either! STRUGGLING!!!
var emailText = templateText.replace("{StudentName}","Joe");templateText.replace("{Sessions}","May - Session#1");templateText.replace("{ChargeAmount}","$500");
// Send Alert Email.
var subject = 'Junior Golf Clinic Registration Receipt';
var message = emailText;
MailApp.sendEmail(emailAddress, subject, message);
}
Here's the result of my existing code which does not properly pull in the values I need.
useremail#gmail.com
9:18 AM (37 minutes ago)
to me
This is the email body.
This is the amount charged to credit card {ChargeAmount}. [Not right. This should be the actual value represented by the var "ChgAmt"]
This is the student's name: Joe [this seems to work when I replace the placeholder {Name} with text like "Joe" but not when I try to replace the placeholder {Name} with the var "studentName"]
These are the sessions the student is scheduled to attend: {Sessions}
[Not right. This should be the actual sessions represented by the var "sessionName"]
Here's more information about the clinics themselves.
This line is incorrect, you're never actually storing your other replace statements.
var emailText = templateText.replace("{StudentName}","Joe");templateText.replace("{Sessions}","May - Session#1");templateText.replace("{ChargeAmount}","$500");
It should be:
var emailText = templateText.replace("{StudentName}","Joe").replace("{Sessions}","May - Session#1").replace("{ChargeAmount}","$500");
As jmcgriz notes, the problem is with the separate calls to .replace. Chaining them fixes your issue.
Here is some dummy code showing what that might look like:
function SendEmail() {
// fetch these values as you need
var studentName = 'Joe'
var sessionName = "May - Session#1";
var emailAddress = 'joe#joe.com'
var chargeAmt = "$500";
// This is what needed to change
var emailText = templateText
.replace("{StudentName}", studentName)
.replace("{Sessions}", sessionName)
.replace("{ChargeAmount}", chargeAmt);
var subject = 'Junior Golf Clinic Registration Receipt';
var message = emailText;
MailApp.sendEmail(emailAddress, subject, message);
}
SendEmail()
<script>
// Mocking MailApp for testing
const MailApp = {
sendEmail: (addr, subj, mess) =>
console.log(`Sending "${addr}" email "${subj}"\n\n${mess}`)
}
const templateText = `
This is the email body.
This is the amount charged to credit card {ChargeAmount}.
This is the student's name: {StudentName}
These are the sessions the student is scheduled to attend: {Sessions}
Here's more information about the clinics themselves.`
</script>

How to use Google Script Send email with group account

I want to send an email with Google Script, but I need to use the public (group) mailbox,
I didn't find an example of sending email from the group account on the Google API, and I couldn't find the answer on the stack overflow. Could you please tell me if there is a method that use google script send email with group account?
I have solved the problem.
from "Account and import" add your group account then You can reference below code to test whether you can send an email in group account.
var alias = GmailApp.getAliases();
var num = alias.length-1;
var myMail = getMyMail();
if (num<0){
return false
}else{
for (var i = 0;i <= num;i++){
if (alias[i] == "yourGroup#Domain.com"){
var myGroupMail=alias[i];
break;
}
}
}
if (myGroupMail != "yourGroup#Domain.com"){return false}
GmailApp.sendEmail(toEmail,strSubject,strContent,{from : myGroupMail});

Google Scripts: Pull Google Document Based on User ID / Email

Good Morning Stack!
I was looking for some advice for some expanded functionality on a Google Script that helps me track and process absence requests. The process is as follows:
A user submits their form responses
The form responses are stored on a spreadsheet
A google doc, pre-created, is pulled and the values from the spreadsheet are implanted in the document.
The document is converted to a PDF
That PDF is automatically emailed to me.
However, some work policies have changed and I now need this form to have a signature that is unique to the person filling the form. In the past we simply printed the resulting PDF and had the person sign off on it.
I know I do not have the technicality to add on any sort of Electronic Signature functionality, nor is emailing that PDF to them an option as it doesn't create a fillable PDF (and my users don't really know how to digitally sign items anyways)
So what I was thinking is to create a form unique to each of the 15-20 users of this process and instead of a getFileByID, have the script check the Google Users account / email and pull the file created for them and stored in my drive instead.
As follows is my current, functional, script. How could I make this work?
function onFormSubmit(e) {
var Last_Name = e.values[2];
var First_Name = e.values[3];
var Middle_Initial = e.values[4];
var Work_Location = e.values[5];
var Job_Title = e.values[6];
var Contact_Number = e.values[7];
var Start = e.values[8];
var End = e.values[9];
var Time = e.values[10];
var Reason = e.values[11];
var D = new Date();
var copyId = DriveApp
.getFileById("1sdfjlsdf55asdfnk565enasdfnsnsd2")
.makeCopy("AbsenceRequest" + Last_Name + Start).getId();
var copyDoc = DocumentApp.openById(copyId)
var copyBody = copyDoc.getActiveSection();
copyBody.replaceText('keyLastName', Last_Name);
copyBody.replaceText('keyFirstName', First_Name);
copyBody.replaceText('keyMiddleInitial', Middle_Initial);
copyBody.replaceText('keyWorkLocation', Work_Location);
copyBody.replaceText('keyJobTitle', Job_Title);
copyBody.replaceText('keyContactNumber',Contact_Number);
copyBody.replaceText('keyStart', Start);
copyBody.replaceText('keyEnd', End);
copyBody.replaceText('keyTime', Time);
copyBody.replaceText('keyDate', D);
copyDoc.saveAndClose();
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
var Email = "email#email.org" + "," + "email#email.org";
var Subject = "Absence Request"
var Body = "This is an absence request"
MailApp.sendEmail(Email, Subject, Body, {attachments: pdf});
DriveApp.getFileById(copyId).setTrashed(true);
}

Categories

Resources