Getting the body of individual emails from gmail to google sheets - google-apps-script

I'm really new at using Google Apps Script, so if what I'm trying doesn't make sense, or just isn't possible please let me know.
Everyday I get several emails that look like the following:
Your Name: FirstName LastName
Phone Number: 555 867 5309
Email Address: FakeEmail#email.com
What do you need help with? Request someone makes.
I'm attempting to automatically send the body of these emails to a new line in a Google Sheet when they come in.
As of right now I have every email get the label "myLabel" when it comes in. I then run the following script, which is a slightly modified version of something I found here:
function myFunction() {
var ss = SpreadsheetApp.getActiveSheet();
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
for (var i=0; i<threads.length; i++)
{
var messages = threads[i].getMessages();
for (var j=0; j<messages.length; j++)
{
var msg = messages[j].getBody();
ss.appendRow([msg])
}
threads[i].removeLabel(label);
}
}
I'm attempting to run this code with a timer trigger every 15 minutes. The issue I've run into is that every time the code runs it pulls from every email in the thread. I would like it to just pull from the emails that are new since the last time it ran. Any advice would be greatly appreciated.

Why not mark the messages as read when you finish processing them? Here is a sample from one of my scripts.
var pendingEmailLabel = "MyLabel";
var threads = GmailApp.getUserLabelByName(pendingEmailLabel).getThreads();
for (var t = 0; t < threads.length; ++t) {
var thread = threads[t];
var messages = thread.getMessages();
for (var m = 0; m < messages.length; ++m) {
var message = messages[m];
if (message.isUnread()) {
// INSERT YOUR CODE HERE THAT TAKES ACTION ON THE MESSAGE
message.markRead();
}
}
}
}

Related

Gmail apps script edit body before forwarding

I'm using Gmail apps script to forward emails with a certain label ... But I'd like to edit the body of the message prior to forwarding.
function fwdFB(){
var label = GmailApp.getUserLabelByName('fb');
var threads = label.getThreads();
for(var m in threads){
var messages = threads[m].getMessages();
for(var y in messages){ messages[y].forward('w#yahoo.com',{from:'webmaster#gmail.com'}) }
threads[m].moveToTrash();
}
}
I'm unclear as to how to insert the getBody() method to edit the message. (Specifically, I want to delete a certain HTML chunk from the message. It's the same chunk in each message.)
The options of forward(recipient, options) do not offer an endpoint to modify the message body. You'll have to do it instead manually, by sending a message after modifying the body as desired.
Sample:
function fwdFB(){
var label = GmailApp.getUserLabelByName('fb');
var threads = label.getThreads();
for(var m in threads){
var messages = threads[m].getMessages();
for(var y in messages){
var oldBody = messages[y].getBody();
var newBody = oldBody.substring(1, 10)+" PS: This is a modification."
var oldSubject = messages[y].getSubject();
var newSubject = "Fwd: "+ oldSubject;
GmailApp.sendEmail('w#yahoo.com', newSubject, newBody, {from:'webmaster#gmail.com'})
}
threads[m].moveToTrash();
}
}
UPDATE
If it is important for you to preserve the message history, you need to perform additional steps to thread the message.
#tehhowch provides a good example of how to do so.

Google Apps substring from null

I put my first Google Apps Script together to write emails to a spreadsheet. It works fine, except of the substring method I would like to use to shorten the message body. The script engine returns "cannot call substring from null […]". I found this thread (google apps script TypeError: Cannot call method "substring" of undefined) but the solution didn't help – or I didn't understand it which is about as likely.
Here's my script.
function labelToSpreadsheet() {
var threads = GmailApp.getUserLabelByName('newaddress').getThreads();
var spreadsheet = SpreadsheetApp.openById("onehellofanID")
var sheet = spreadsheet.getSheets()[0];
Logger.log (spreadsheet.getName());
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var shortendContent = messages[j].getPlainBody().substring(0, 500);
sheet.appendRow([messages[j].getSubject(), messages[j].getFrom(), messages[j].getReplyTo(), messages[j].getDate(), shortendContent]);
}
}
};
This was driving me nuts, as there was no reason your code wouldn't work, and I was getting the same error. I narrowed it down to the 'getPlainBody()' was returning 'null', but couldn't figure out why this was the case even when I used GMails own example.
I was almost going to call it a bug when I realized that what was happening was that some messages were returning nothing in the body. Specifically, some companies send out newsletters that aren't text content at all, but in fact are images with their content inside (Which was the case with the first message in the test label I had, thus driving me bonkers).
So, the issue here is that the label you're running this under has some messages where the content is only an image, no text whatsoever (Or potentially, is just completely blank), thus 'getPlainBody()' returns 'There's nothing there'(Null) and you can't get a substring of nothing.
A simple 'if' statement actually handles this error really well, as you can then tell the script to write to the sheet 'The content of this message was an image' (Or whatever you want).
This slightly modified version of your code works for me:
function labelToSpreadsheet() {
var threads = GmailApp.getUserLabelByName(LABELNAME).getThreads();
var spreadsheet = SpreadsheetApp.openById(SHEETID);
var sheet = spreadsheet.getSheets()[0];
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
if(messages[j].getPlainBody() == null){
var shortendContent = 'This message was an image';
}else{
var shortendContent = messages[j].getPlainBody().substring(0, 500);
};
sheet.appendRow([messages[j].getSubject(), messages[j].getFrom(), messages[j].getReplyTo(), messages[j].getDate(), shortendContent]);
}
}
};
I'm giving myself a gold star for this one, it was annoying to figure out.

reply time between threads [google apps script]

I want to develop a script in GAS to get the reply time of all of my threads in Gmail in a specific period. The example script below seems to be a way, but im not sure on how to proceed.
function processInbox() {
// get all threads in inbox
var threads = GmailApp.getInboxThreads();
for (var i = 0; i < threads.length; i++) {
// get all messages in a given thread
var messages = threads[i].getMessages();
// iterate over each message
for (var j = 0; j < messages.length; j++) {
// log message subject
Logger.log(messages[j].getSubject());
}
}
};
Maybe use:
Google Documentation - getDate() GmailMessage Class
When you say you want to "get" the information, how do you want to get it? Be sent an email? Store it in a spreadsheet? Record it in a .csv file?

Google Apps Script for Gmail Deletion

I use a simple Script to delete all emails after 1 day if they are labelled 'camera'. This has been working for months. I haven't changed it but it suddenly stopped working.
The script still has permission to run on my Gmail but has stopped.
Any advice appreciated.
The script is;
function cleanUp() {
var delayDays = 1 // Enter # of days before messages are moved to trash
var maxDate = new Date();
maxDate.setDate(maxDate.getDate()-delayDays);
var label = GmailApp.getUserLabelByName("camera");
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
if (threads[i].getLastMessageDate()<maxDate)
{
threads[i].moveToTrash();
}
}
}
Thanks,
Sam
Can you log over the loop to check if it's iterating?

Google Apps Script - Read data from gmail specific label returns messages from all labels

There are 2 user defined labels in my gmail named x & y. I need to retrieve the messages present in that specific label, but am getting the data from all the labels.
I need Msg body, label and date received and update it in spreadsheet
Following is my code:
var ulables = GmailApp.getUserLabels();
for(var x=0; x < ulables.length; x++){
var threads = GmailApp.getUserLabelByName(ulables[x].getName()).getThreads();
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
var label = ulables[x].getName();
for (var m = 0; m < messages.length; m++) {
var msg = messages[m].getBody();
var cmsg = convertHtmlToText(msg);
var subject = messages[m].getSubject();
if(subject == reqSub){
var recDate = Utilities.formatDate(messages[m].getDate(),"GMT","MM/dd/yyyy");
if(isDateInRange(recDate, startDate, endDate)){
var arr =[recDate,label,cmsg];
mailSheet.getRange(++lastRow, 1,1,3).setValues([arr]).activate();
}
}
}
}
}
Ex:- Label x has 10 emails
Label y has 10 emails
Inbox has 50 emails
For each label, am getting 60 emails which is the problem, but I expect 10,10,50 emails.
Have been struggling it from last 2 days, but not succeeded. Please help me. Thanks a ton in advance.
Please let me know the details, have been waiting for it from last one week. Is there any way getting messages without using threads?