I need to generate a report on the list of messages and the sender of a letter, I can extract the theme of letters, but not understanding how to get the sender's address for each letter, the report turned out to be:
topic: hello From: frank#gmail.com
topic: your basket from: jerry#facebook.com
function myFunction() {
var emailAddress = Session.getActiveUser().getEmail();
var threads = GmailApp.getInboxThreads();
var output = ContentService.createTextOutput();
for (var i = 0; i < threads.length; i++) {
output.append(threads[i].getFirstMessageSubject()+" from:"+'\n');
}
GmailApp.sendEmail(emailAddress,"Mail Report", output.getContent()
);
}
UPDATE
Thank you for your answers, the solution was simple
function myFunction() {
var emailAddress = "example#email.com" ;
var threads = GmailApp.getInboxThreads();
var messages = threads[0].getMessages();
var senderEmail = messages[0].getFrom();
var output = ContentService.createTextOutput();
for (var i = 0; i < threads.length; i++) {
messages = threads[i].getMessages()
senderEmail = messages[0].getFrom();
output.append(i + ". " + threads[i].getFirstMessageSubject()+" from:"+ senderEmail + '\n');
}
GmailApp.sendEmail(emailAddress,"Mail Report", output.getContent()
);
}
Example result:
Email Verification - Stack Overflow from:Stack Overflow
Project Update #10: Double Fine Adventure by Double Fine and 2 Player Productions from:Kickstarter
If I understand what you are looking to do, then I believe you could get the messages from the thread, and then the sender from the message
var threads = GmailApp.getInboxThreads();
var messages = threads[0].getMessages();
var senderEmail = messages[0].getFrom();
var label = GmailApp.getUserLabelByName('inbox');
var threads = label.getThreads();
for(i in threads)
{
threads[i].getMessages()[0].getFrom()
}
You need to add
"https://www.googleapis.com/auth/userinfo.email"
in oauthScopes.(appscript.json file)
you can get more details in this link
enter link description here
For reasons of security, you cannot get the email using Session.getActiveUser().getEmail() if you are on a consumer Google account. It works only when the script is owned by a Google Apps user and the visitor belongs to the same domain.
However, you can try what is mentioned here
Related
My fellow teachers and I like to send students little google drawings to let them know they've been doing well lately. We have a spreadsheet that we use and I am trying to automate the process of sending them an email when their drawing is ready to be viewed. I keep getting the 'Cannot read property 'getRange' of null error' even though I am 100% sure that a sheet exists with the name PR and that it is spelled right. I am new to Google Script so I lack the skills to troubleshoot any more than the googling I've done already, which basically just says to make sure you've named the sheet correctly. Any help would be very appreciated!
var studentFirstNameRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PR').getRange("A2:A");
var studentFirstname = studentFirstNameRange.getValues();
var studentEmailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PR').getRange("D2:D");
var studentEmail = studentEmailRange.getValues();
var emailSendRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PR').getRange("L2:L");
var emailSend = emailSendRange.getValues();
if (emailSend){
// Send Alert Email.
var message = 'Hi ' + studentFirstname + '! Your teachers noticed you have been doing a great job this year, so we made this for you! Keep up the great work!' ; // Second column
var subject = 'Positive Recognition';
MailApp.sendEmail(studentEmail, subject, message);
}
}```
According to the title and the error you related, I did'nt get any error.
However, I don't understand your condiiton if (emailSend) neither the way you send emails. If you send emails to all the population at once, you can try
function myFunction() {
var lastRow = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PR').getLastRow()
var studentFirstNameRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PR').getRange("A2:A"+lastRow);
var studentFirstname = studentFirstNameRange.getValues();
var studentEmailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PR').getRange("D2:D"+lastRow);
var studentEmail = studentEmailRange.getValues();
var emailSendRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PR').getRange("L2:L"+lastRow);
var emailSend = emailSendRange.getValues();
if (emailSend){
// Send Alert Email.
var message = 'Hi ' + studentFirstname + '! Your teachers noticed you have been doing a great job this year, so we made this for you! Keep up the great work!' ; // Second column
var subject = 'Positive Recognition';
Logger.log(studentEmail.join())
MailApp.sendEmail(studentEmail.join(), subject, message);
}
console.log('there is no errors!')
}
if you want to send individually
function myFunction() {
var lastRow = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PR').getLastRow()
var studentFirstNameRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PR').getRange("A2:A" + lastRow);
var studentFirstname = studentFirstNameRange.getValues();
var studentEmailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PR').getRange("D2:D" + lastRow);
var studentEmail = studentEmailRange.getValues();
var emailSendRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PR').getRange("L2:L" + lastRow);
var emailSend = emailSendRange.getValues();
for (var i = 0; i < studentFirstname.length; i++) {
if (emailSend[i][0]) {
// Send Alert Email.
var message = 'Hi ' + studentFirstname[i][0] + '! Your teachers noticed you have been doing a great job this year, so we made this for you! Keep up the great work!'; // Second column
var subject = 'Positive Recognition';
MailApp.sendEmail(studentEmail[i][0], subject, message);
}
}
}
I am using Google sheets and the Google script editor to create a script to automatically send myself an e-mail every time a product quantity goes below the minimum inventory level. Since I have multiple products with different minimum inventory levels I expect to get a series of e-mails, one for each row.
I use one sheet for the actual Inventory data and another sheet that contains information for the script to refer to, such as my email and what message to include in the e-mail.
I succeeded having an e-mail sent collecting data from the first row of the Inventory sheet but I am not being able to apply that for all the following rows.
I tried changing the .getRange("F2") to .getRange("F2:F"), then whenever one of the products goes under the minimum inventory level I get one single e-mail containing the information about all products, regardless of whether their quantity is under the minimum level or not.
The ideal solution would be ONE single e-mail containing all the information about all products that are under the minimum quantity .
Here is a link to my spreadsheet: https://docs.google.com/spreadsheets/d/1ZHmBvi8ZeaDRYq6Qigaw08NUiOwZumPrLnvnka_mgmA/edit?usp=sharing
Current script:
function CheckInventory() {
// Fetch inventory quantity
var InventoryRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inventory").getRange("F2");
var Inventory = InventoryRange.getValue();
// Fetch minimum quantity
var MinimumQuantityRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inventory").getRange("D2");
var MinimumQuantity = MinimumQuantityRange.getValue();
// Check Inventory
if (Inventory < MinimumQuantity){
// Fetch email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Notification Rules").getRange("E2");
var emailAddress = emailRange.getValues();
// Fetch email message details.
var detailsRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Notification Rules").getRange("G2");
var details = detailsRange.getValues();
var subjectdetailsRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Notification Rules").getRange("H2");
var subjectdetails = subjectdetailsRange.getValues();
// Send Alert Email.
var message = details;
var subject = subjectdetails;
MailApp.sendEmail(emailAddress, subject, message);
}
}
Update:
As you said in a comment, you want the email to be sent when you edit an inventory cell, and only if this edited inventory quantity is below the corresponding minimum. So here I update my answer accordingly.
First, I guess you have done this already, but because the function uses sendEmail, you will have to grant authorization for it to work. I created a trigger for that. Run this once:
function createEditTrigger() {
var ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger("CheckInventory")
.forSpreadsheet(ss)
.onEdit()
.create();
}
Then, this is the function that will run every time the spreadsheet is edited. To avoid the email to be sent every time the file is edited, we need a condition that checks whether the edited cell is an inventory and that this inventory is below the minimum:
function CheckInventory(e) {
var ss = e.source;
var inventorySheet = ss.getSheetByName("Inventory");
var rowIndex = e.range.getRow();
var columnIndex = e.range.getColumn();
var numCols = 6;
var row = inventorySheet.getRange(rowIndex, 1, 1, numCols).getValues()[0];
var editedInventory = row[5];
var editedMinimum = row[3];
var sheetName = ss.getActiveSheet().getName();
// Checking that: (1) edited cell is an inventory quantity, and (2) Inventory is below minimum
if(editedInventory <= editedMinimum && sheetName == "Inventory" && columnIndex == 6 && rowIndex > 1) {
var inventoryValues = inventorySheet.getDataRange().getValues();
var emailBody = "";
for(var i = 1; i < inventoryValues.length; i++) {
var inventory = inventoryValues[i][5];
var minimum = inventoryValues[i][3];
if(inventory <= minimum) {
var productName = inventoryValues[i][0] + " " + inventoryValues[i][1];
var productUnits = minimum + " " + inventoryValues[i][4];
var messagePart1 = "Inventory for " + productName + " has gone under " + productUnits + ". ";
var messagePart2 = "Organise purchase order. Inventory as of today is: " + inventory + " " + inventoryValues[i][4];
var message = messagePart1.concat(messagePart2);
var newItem = "<p>".concat(message, "</p>");
emailBody += newItem;
}
}
var emailSubject = "Low inventory alert";
var emailAddress = "your-email#your-domain.com";
// Send Alert Email
if(emailBody != "") {
MailApp.sendEmail({
to: emailAddress,
subject: emailSubject,
htmlBody: emailBody
});
}
}
}
As I said in a comment, if you just want to send an email, it doesn't make sense to have many email subjects, so I hardcoded the subject.
Regarding the emails, I assumed you just want an email address to receive the email, so I hardcoded it too. If you want all the different email addresses found in Notifications tab to receive emails regarding all products, a small fix would be needed to this code. Tell me if that's needed for you.
Also, I didn't use your notifications tab at all, I created the message directly using the script. I'm not sure it is that useful to have the sheet "Notification Rules". Much of its info is the same as the one in inventory, and the rest of data (email address, basically) could be easily included there. But whatever suits you.
I hope this is of any help.
I'm new to Google Apps script and am trying to add an image inline to an automated response email.
The auto reply works perfectly, the main text of the email formats well in plain text and html.
the problem i'm facing is that the image does not appear.
my code:
// This constant is written in column Y for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'EMAIL_SENT';
/**
* Sends non-duplicate emails with data from the current spreadsheet.
*/
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Data'))
var startRow = 2; // First row of data to process
// Fetch the range
var dataRange = sheet.getRange("L2:L1000")
var dataRange2 = sheet.getRange("K2:K1000")
var dataRange3 = sheet.getRange("O2:O1000")
var dataRange4 = sheet.getRange("Y2:Y1000")
var dataRange5 = sheet.getRange("B2:B1000")
// Fetch values for each row in the Range.
var data = dataRange.getValues();
var data2 = dataRange2.getValues();
var data3 = dataRange3.getValues();
var data4 = dataRange4.getValues();
var data5 = dataRange5.getValues();
for (var i = 0; i < data.length; ++i) {
var yesno = data2[i]
if(yesno == "Yes"){
var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = UrlFetchApp
.fetch(TFlogoUrl)
.getBlob()
.setName("TFlogoBlob");
var emailAddress = data[i];
var ShipID = data3[i];
var cmdrID = data5[i];
var TFmsg = "Hi " + cmdrID + ",/n /nThank you for signing up to The Fatherhoods Lost Souls Expedition./n /nYour unique Ship ID is: " + ShipID + "/n /nWe look forward to seeing you on the expedition CMDR!/n /nFly Safe,/nThe Lost Souls Expedition team.";
var htmlTFmsg = "Hi " + cmdrID + ",<br> <br>Thank you for signing up to The Fatherhoods Lost Souls Expedition.<br> <br>Your unique Ship ID is: " + ShipID + "<br> <br>We look forward to seeing you on the expedition CMDR!<br> <br>Fly Safe,<br>The Lost Souls Expedition team.<br><img src='cid:TFlogo'>";
emailSent = data4[i]; // email sent (column Y)
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = "Lost Souls Expedition Sign up confirmation";
MailApp.sendEmail(emailAddress,subject,TFmsg,{
htmlBody: htmlTFmsg,
inlineImage:
{
TFlogo:TFlogoBlob
}
});
sheet.getRange("Y" + (startRow + i)).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
}
How about this modification?
Modification points:
You cannot retrieve the file blob from this URL var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";. If you want to retrieve the file blob from URL, please use var TFlogoUrl = "http://drive.google.com/uc?export=view&id=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";. 1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287 is the file ID.
As an another method, from the file ID, it is found that the values of getSharingAccess() and getSharingPermission() are ANYONE_WITH_LINK and VIEW, respectively. So you can also retrieve the blob using var TFlogoBlob = DriveApp.getFileById("1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287").getBlob().setName("TFlogoBlob");. I recommend this.
When you want to use the inline image to email, please modify from inlineImage to inlineImages.
The script which reflected above points is as follows.
Modified script:
Please modify your script as follows.
From:
var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = UrlFetchApp.fetch(TFlogoUrl).getBlob().setName("TFlogoBlob");
To:
var id = "1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = DriveApp.getFileById(id).getBlob().setName("TFlogoBlob");
And
From:
inlineImage: {TFlogo:TFlogoBlob}
To:
inlineImages: {TFlogo:TFlogoBlob}
References:
sendEmail(recipient, subject, body, options)
If I misunderstand your question, please tell me. I would like to modify it.
I am trying to create a script that will forward the latest message in any thread with a particular label ('send-to-test') to a specific group of contacts ('fwd-test'). I based it heavily on StackExchange: How can I automatically forward Gmail emails when a label is applied?
The script I've come up with so far is below:
function autofwd() {
//target mail label
var inlabel = 'send-to-test';
Logger.log("Target mail label is: " + inlabel);
//processed mail label
var outlabel = 'sent-to-test';
Logger.log("processed mail label is: " + outlabel);
//Retrieve contacts list to fwd to
var group = ContactsApp.getContactGroup('fwd-test');
var contacts = ContactsApp.getContactsByGroup(group);
var email = new String();
for (var i=0; i<contacts.length; i++)
email = contacts[i].getPrimaryEmail() + ',' + email;
Logger.log("email address list is: " + email);
//Find message threads matching the label variable and do something to each one
var threads = GmailApp.search('label:' + inlabel);
for (var i = 0; i < threads.length; i++) {
//isolate the last message in the thread and forward it using bcc field
var messages = threads[i].getMessages();
Logger.log("Working on message: " + messages);
messages[messages.length - 1].forward({bcc: email});
// add 'sent' label and remove 'send' label
var addlabel = GmailApp.getUserLabelByName(outlabel);
addlabel.addToThread(threads[i]);
var notlabel = GmailApp.getUserLabelByName(inlabel);
notlabel.removeFromThread(threads[i]);
}
}
The issue is I want to forward the emails as BCC, but I cant get that line of code to work:
messages[messages.length - 1].forward({bcc: email});
fails with the error Invalid email: [object Object] (line 22, file "Code")
But it works fine if I just use messages[messages.length - 1].forward(email);
Can someone help me understand what I'm doing wrong?
How about this modification?
From :
messages[messages.length - 1].forward({bcc: email});
To :
messages[messages.length - 1].forward("", {bcc: email});
Reference :
forward(recipient, options)
If I misunderstand your question, I'm sorry.
Problem: Daily we get a dozen of mails. We need to print all of them in regular basis. Is it possible for a Google Apps Script to read only the unread mails and to store them in a Google Doc? No HTML nothing, I just need the plain text in the following format.
​From: S. Banerjee Date: 3 January
2017 at 02:40 Subject: Re: Happy New Year To: "Br. Sayan"
...... ...... Message ..... ......
I was searching for a solution, but only managed to get something like the following here. Now we need to get the msgIDs of the unread mail pass them on to the function. Rest of the formatting can be solved later on piecemeal basis I think.
function saveGmail(msgID) {
// Based on Drive Scoop
// Available at https://github.com/google/gfw-deployments
var message = GmailApp.getMessageById(msgID);
// Grab the message's headers.
var from = message.getFrom();
var subject = message.getSubject();
var to = message.getTo();
var cc = message.getCc();
var date = message.getDate();
var body = message.getBody();
// Begin creating a doc.
var document = DocumentApp.create(subject);
var document_title = document.appendParagraph(subject);
document_title.setHeading(DocumentApp.ParagraphHeading.HEADING1);
var style = {};
style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = (DocumentApp.HorizontalAlignment.CENTER);
document_title.setAttributes(style);
var headers_heading = (document.appendParagraph("Gmail Message Headers"));
headers_heading.setHeading(DocumentApp.ParagraphHeading.HEADING2);
AddGmailHeaderToDoc(document, "From", from);
AddGmailHeaderToDoc(document, "To", to);
AddGmailHeaderToDoc(document, "Cc", cc);
AddGmailHeaderToDoc(document, "Date", date);
AddGmailHeaderToDoc(document, "Subject", subject);
var body_heading = (
document.appendParagraph("Body (without Markup)"));
body_heading.setHeading(DocumentApp.ParagraphHeading.HEADING2);
var sanitized_body = body.replace(/<\/div>/, "\r\r");
sanitized_body = sanitized_body.replace(/<br.*?>/g, "\r");
sanitized_body = sanitized_body.replace(/<\/p>/g, "\r\r");
sanitized_body = sanitized_body.replace(/<.*?>/g, "");
sanitized_body = sanitized_body.replace(/'/g, "'");
sanitized_body = sanitized_body.replace(/"/g, '"');
sanitized_body = sanitized_body.replace(/&/g, "&");
sanitized_body = sanitized_body.replace(/\r\r\r/g, "\r\r");
var paragraph = document.appendParagraph(sanitized_body);
document.saveAndClose();
return document.getUrl();
}
function AddGmailHeaderToDoc(document, header_name, header_value) {
if (header_value === "") return;
var paragraph = document.appendParagraph("");
paragraph.setIndentStart(72.0);
paragraph.setIndentFirstLine(36.0);
paragraph.setSpacingBefore(0.0);
paragraph.setSpacingAfter(0.0);
var name = paragraph.appendText(header_name + ": ");
name.setBold(false);
var value = paragraph.appendText(header_value);
value.setBold(true);
}
Your help will be very much appreciated!!
An easier way might be to use 'is:unread' search
var threads = GmailApp.search('is:unread');
var messages = threads[0].getMessages();
for (var i = 0; i < messages.length; i++) {
Logger.log(messages[i].getId());
}
This will log the Id's but you can return them as well. Also note that threads and messages are different. The above will get the first unread thread and all the messages in this thread (even if the messages are read).