Count number of email sent to a person - google-apps-script

I am trying to get the number of times that a person has been sent an email, so I can keep track of leads, for example
user#domain.com was emailed 5 times
user2#domain.com was emailed 3 times
From reading the docs I cannot figure this one out
Is this possible?
EDIT:
function myFunction(e) {
e = "someemail#gmail.com";
var threads = GmailApp.search("to:" + e + "");
var count = 0;
for (var i = 0; i < threads.length; i++) {
count++;
}
Logger.log(count) //1
}
This gives me threads but no number of messages

I think you are on the right lines using search() to find the sent items. This is a snippet I use to scan through all the unread emails in the inbox, and the processing that email. You'll want something similar:
var totalThreads = GmailApp.getInboxThreads().length
// Read in READ_AT_ONCE pages of email at a time
for (var pageindex = 0; pageindex < totalThreads; pageindex += READ_AT_ONCE) {
var threads = GmailApp.getInboxThreads(pageindex, READ_AT_ONCE)
var msgs = GmailApp.getMessagesForThreads(threads)
var numThreads = threads.length
// Read in all the threads in the batch
for (var threadIndex = 0; threadIndex < numThreads; threadIndex++) {
var numMsgs = msgs[threadIndex].length
// Process each msg in the thread
for (var msgIndex = 0; msgIndex < numMsgs; msgIndex++) {
var msg = msgs[threadIndex][msgIndex]
if (!msg.isUnread() || msg.isInTrash()) {
continue
}
Email_.processMsg(msg)
} // for each msg
} // for each thread
} // for each batch

Related

Google Apps Script Why it only searches for one (first) attachment

I have two codes, the first of which works and shows all attachments and the second shows only the first. "getAttachmentAndMessage" is used by several of my scripts so I need to have it in a separate function in order not to duplicate my configuration. Please help.
//this function get me all attachments
//this function is just an example of how I built my code below;
function searchEmailsData(){
var search = GmailApp.search('in:inbox newer_than:3d');
var threads = GmailApp.getMessagesForThreads(search);
for (var i = 0 ; i < threads.length; i++) {
var thread = threads[i];
for (var j = 0; j < thread.length; j++) {
var message = thread[j];
var attachments = message.getAttachments();
for (var k = 0; k < attachments.length; k++) {
var attachment = attachments[k];
Logger.log(attachment.getName());
}
}
}
}
//this functions get me only first attachment but I need all of them;
function searchEmailsData2(){
var search = GmailApp.search('in:inbox newer_than:3d');
var threads = GmailApp.getMessagesForThreads(search);
for (var i = 0 ; i < threads.length; i++) {
var thread = threads[i];
var obj = getAttachmentAndMessage(thread);
Logger.log(obj[1].getName())
}
}
function getAttachmentAndMessage(thread){
for (var j = 0; j < thread.length; j++) {
var message = thread[j];
var attachments = message.getAttachments();
for (var k = 0; k < attachments.length; k++) {
var attachment = attachments[k];
var obj = [message, attachment];
return obj;
}
}
}
In order to return not the first attachment but rather all of them, you can modify the getAttachmentAndMessage() function as follows:
function getAttachmentAndMessage(thread) {
var results = [];
for (var j = 0; j < thread.length; j++) {
var message = thread[j];
var attachments = message.getAttachments();
var obj = {'message': message, 'attachments': attachments};
results.push(obj);
}
return results;
}
The above will return a list of objects, in which each objects contains a property message, and a property attachments (which is a list of attachments).
In order to return a list containing only the attachments in the thread, you can use the following variation of the code above:
function getAttachmentAndMessage(thread) {
var results = [];
for (var j = 0; j < thread.length; j++) {
var message = thread[j];
var attachments = message.getAttachments();
results = results.concat(attachments);
}
return results;
}
Your original code
In your original getAttachmentAndMessage() code, you were using a return statement inside of the for loop. That means that upon finding the first message (first iteration of the outer loop) and upon finding its first attachment (first iteration of the inner loop) the function would simply return one value, which is a list containing the first message and its first attachment.

Count all eMails from a Label

i have create this script:
function myTest() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var label = GmailApp.getUserLabelByName("Label1");
var threads = label.getThreads();
var countMail = 0;
//get first message in first thread
for (var i = 0; i < threads.length; i++) {
var messages=threads[i].getMessages();
countMail = countMail + messages.length;
}
ss.getRange(1,1).setValue(countMail);
}
it runs nearly perfect. Here I get all eMails back which are connected with this treads (marked with Label1 or not).
Does anyone can share a simply script how I can count all eMails which are "realy" marked with the Label.
Thanks
Try this:
function labelMsgs(){
var labels = Gmail.Users.Labels.list("me").labels;
var lblId;
for (var i = 0; i < labels.length; i ++){
if (labels[i].name == "Label1"){
lblId = labels[i].id;
break;
}
}
var optionalArgs = {
"labelIds" : lblId,
"maxResults" : 200
}
var messages = Gmail.Users.Messages.list("me", optionalArgs).messages;
}
This method uses the Gmail API directly, for this you'll need to enable Google Advanced Services, it will return a list of all messages tagged with the "Label1" label. You can play around with maxResults and with the pageToken to see more results, but this is the general approach.

Gmail App: Find threads which have a calendar entry

Some messages have calendar entries at the top of them like this:
In GScript, is there any way to find messages which have these calendar entries? If so, how does one extract the information from it?
Update
I took a lucky shot and found that it's classed as an attachment (of type ics), but there still remains the issue of extracting the data from this file...
Try this:
function getIcs(){
var threads = GmailApp.getInboxThreads();
var thread, messages, message, attachments, attachment;
var result = [];
for (var i = 0; i < threads.length; i++){
messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++){
message = messages[j];
attachments = message.getAttachments();
for (var k = 0; k < attachments.length; k++){
attachment = attachments[k];
if(attachment){
if (attachment.getContentType() == "application/ics"){
Logger.log("found ics");//continue;
result.push(message);
}
}
}
}
}
return result;
}
This method will view every thread, every message in it and every attachment in each message, and returns a list of the message objects that have an attachment of type application/ics.
UPDATE
In addition to my previous code, the following function will return an array of event objects based on the attachments found in the other method:
function getSutff(){
var msgs = getIcs();
var ics;
var position;
var eventId;
var event = [];
for (var i = 0; i < msgs.length; i++){
ics = msgs[i].getAttachments()[0].getDataAsString();
position = (ics.search("UID:")) + 4;
eventId = ics.substr(position,26);
event.push(CalendarApp.getEventById(eventId));
}
Logger.log(event)
return event;
}

Need to split the row based on Error and Warning and remove particular content

While run the provided script its working perfect, but need to modify. this is the screenshot tells what i need, i am trying to change script , please help me if you can
function autocopy() {
var label = GmailApp.getUserLabelByName("Sanmina EDI Failed Concurrent Jobs Alert");
var threads = label.getThreads();
var read = threads.getMessages();
var uread = threads.isUnread();
for(var i = 0; i <= uread.length; i++) {
var message=uread(i);
}
var message1 = new message.Date();
var day = message1.getUTCDate();
var bodycontent = message.getbody();
var action = bodyContents.search("Invoice")
var action1 = bodyContents.search("Error")
var action2 = bodyContents.search("Terminated")
if (action > 0) {
var out ="Need to create SR"
} else if (action1 > 0 || action2 > 2) {
var out ="Need to create SR"
} else {
var out ="Printing output file"
}
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([day, bodycontent, out]);
}
I want to extract the data from email to spreadsheet,by reading unread thread id and using for looping the reach from read thread id to unread thread id and print the mail body content and date from the unread email.
I reworked your code a bit. Put some comments in it so that you can see clearly what is happening in each line. Your issue was that you were trying to use methods on the wrong objects (for example, an array of threads does not have a getMessages method, so you have to loop through each thread and get the messages for each specific thread).
function autocopy() {
var label = GmailApp.getUserLabelByName("Sanmina EDI Failed Concurrent Jobs Alert");
// Get all threads belonging to this label
var threads = label.getThreads();
// Loop through each thread
for (var i = 0; i < threads.length; i++) {
// Check whether thread is unread
if (threads[i].isUnread()) {
// Get all messages for each unread thread
var messages = threads[i].getMessages();
// Loop through all messages for each unread thread
for (var j = 0; j < messages.length; j++) {
// Check whether message is unread
// (delete this condition if you want all messages in an unread
// thread to be printed in your spreadsheet, read or unread)
if (messages[j].isUnread()) {
var day = messages[j].getDate();
var bodyContent = messages[j].getBody(); // Use getPlainBody() instead if you don't want html tags;
var action = bodyContent.search("Invoice");
var action1 = bodyContent.search("Error");
var action2 = bodyContent.search("Terminated");
if (action > 0) {
var out = "Need to create SR"
} else if (action1 > 0 || action2 > 2) {
var out = "Need to create SR"
} else {
var out = "Printing output file"
}
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([day, bodyContent, out])
}
}
}
}
}
I hope this works for you!

Why doesn't this script collect all gmails?

I have a google app script that collects information about Gmail messages and then pastes it into a google sheet. Trouble is it doesn't get ALL of the messages. It only picks up the first one of each thread. I feel like I am missing something to loop through each thread? Any suggestions?
function getMail(){
var myspreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var mysheet = myspreadsheet.getSheetByName("Sheet3");
var start = 0;
var max = 99;
var count =0;
var row = mysheet.getLastRow()+1
var maxDate = mysheet.getRange("B1").getValue()
while(count < 4)
{
var threads = GmailApp.getInboxThreads(start , max);
var messages = GmailApp.getMessagesForThreads(threads);
var froms = [];
messages.get
for(var i = 0; i < threads.length; i++)
{
var msgDate = messages[i][0].getDate();
if(msgDate>maxDate){
froms.push([messages[i][0].getDate(),messages[i][0].getFrom(),messages[i][0].getSubject(),messages[i][0].getPlainBody()]);
}
}
if(froms.length>0){
mysheet.insertRows(2, froms.length)
mysheet.getRange(2,1,froms.length,4).setValues(froms);
}
start = start + 100;
count++;
}
}
Your current script is only grabbing messages[i][0], the first message in that group for the thread. Instead you need to loop through all of the messages using two for loops, as you can see in the script below I use messages[i][j].
function getMail() {
var mySpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var mySheet = mySpreadsheet.getSheetByName("Sheet3");
var start = 0;
var max = 99;
var count = 0;
var maxDate = mySheet.getRange("B1").getValue();
while(count < 4) {
var threads = GmailApp.getInboxThreads(start, max);
var messages = GmailApp.getMessagesForThreads(threads);
var froms = [];
for(var i = 0; i < messages.length; i++) {
for(var j = 0; j < messages[i].length; j++) {
var msgDate = messages[i][j].getDate();
if(msgDate > maxDate) {
froms.push([msgDate,messages[i][j].getFrom(),messages[i][j].getSubject(),messages[i][j].getPlainBody()]);
}
}
}
if(froms.length > 0) {
mySheet.insertRows(2, froms.length);
mySheet.getRange(2, 1, froms.length, 4).setValues(froms);
}
start = start + 100;
count++;
}
}
Notable changes:
removed var rows because it wasn't used anywhere in the script.
changed first for loop to run for messages.length rather than
threads.
added another for loop to loop through every message in
messages[i].
you were getting messages[i][0].getDate() twice, so I just used the variable already defined for adding to the array.
minor grammatical/spacing changes for consistency across script.