Google Apps Script: Unable to send emails using createEvent() - email

I have the following code and attendees are not able to receive emails about the event. Though the event is reflecting in their calendar.
var options = {
description: description,
location: location,
guests: email_address,
sendInvites: true
}
var event = CalendarApp.getCalendarById(calendarId).createEvent(title,
start_datetime, end_datetime,
options);
I have added oauthScopes to appsscript.json as well.
"oauthScopes": [
"https://www.googleapis.com/auth/calendar",
"https://www.google.com/calendar/feeds"
]
It seems like an authorization issue but not sure how to solve this.

You don't need to manually add any scopes while running the script from the browser editor.
Your code worked perfectly for me :) I added a few variables to complete it but it worked just fine -
function myFunction() {
var calendarId = 'self#gmail.com'; // if using your own or default calendar ID
var description = 'test desc';
// ref link - https://developers.google.com/apps-script/reference/calendar/calendar-app#advanced-parameters_4
var email_address = 'contact1#gmail.com, contact2#gmail.com';
// comma separated guest list
var title = 'test title';
var start_datetime = new Date();
var end_datetime = new Date();
var options = {
description: description,
guests: email_address,
sendInvites: true
}
var event = CalendarApp
.getCalendarById(calendarId)
.createEvent(title, start_datetime, end_datetime, options);
}
My default manifest file looks like this -
{
"timeZone": "Asia/Kolkata",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER"
}
No additional scopes seem to have been added. However, when I view my File > Project properties > Scope, only a single scope seem to have been added by the script -
OAuth Scope required by script:
https://www.googleapis.com/auth/calendar
Hope this helps.
Edit note: Forgot to add -
Email notifications are being received as well

Related

Send email to the new google form submission only

I'm new to the Google apps script. I wrote a script to send emails when there is a new submission from google forms using data and template from a spreadsheet. However, it sends an email to not just the new submission but also to all of the previous submissions. The whole script is quite long, so I only copy a short part of it. Is there any way to fix it?
Here is the link to the spreadsheet https://docs.google.com/spreadsheets/d/1fhuwEndIS3khg3W19jpQnBAaCp_MMrD_bfATrdf2-4I/edit?usp=sharing
Thank you.
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Calculation");
var lr = ss.getLastRow();
for (var i = 3; i<=lr;i++){
var currentEmail = ss.getRange(i, 1).getValue();
var currentName = ss.getRange(i, 3).getValue();
var currentScore1 = ss.getRange(i, 4).getValue();
MailApp.sendEmail(
currentEmail,
subjectline,
"HTML",
{ htmlBody: messageBody }
);
}
}
Instead of reading the values from the spreadsheet take advantage of the form submit event object. This event object has two properties including the form submission values, one is an Array of form submission values in the same order than the sheet columns, the other is an object having a property for each question each of them having an Array of values. Ref. https://developers.google.com/apps-script/guides/triggers/events
This shows the changes that need to done to your script:
function sendEmail(e) {
var currentEmail = e.values[0];
var currentName = e.values[2];
var currentScore1 = e.values[3];
MailApp.sendEmail(
currentEmail,
subjectline,
"HTML",
{ htmlBody: messageBody }
);
}
Note: In order to make the event object work, the function should be called by a Google Sheets form submit trigger.
Related
Event values and offset in Google spreadsheet
How to send an email only to the last Google form submission?

Google Sheets App Script- Add signature when sending e-mail

I'm working on a script that will save my Google Sheet spreadsheet as a pdf and email it as an attachment. The code I'm using works, but I don't know how to add a signature to the email I'm sending. Is this possible, and if so; what would be the cleanest way to do it? Here's the code I'm working with. I know, it's not pretty.
function displayPrompt() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheetName = ss.getActiveSheet().getName();
var ui = SpreadsheetApp.getUi();
var result = ui.prompt("Please enter email body");
//Get the button that the user pressed.
var button = result.getSelectedButton();
var message = {
to: "someone#somewhere.com",
subject: sheetName,
body: "Hi team,\n\nPlease find attached the quote that you requested.\n" +
result.getResponseText() + "\nThank you,\nMe",
name: "My Name",
attachments:
[SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("Quote")]
}
if (button === ui.Button.OK) {
Logger.log("The user clicked the [OK] button.");
Logger.log(result.getResponseText());
MailApp.sendEmail(message);
} else if (button === ui.Button.CLOSE) {
Logger.log("The user clicked the [Cancel] button.");
}
}
I believe your goal as follows.
You want to add the signature to the message of Gmail using MailApp.sendEmail
In this case, I think that there are 2 patterns.
Pattern 1:
In this pattern, by declaring the signature as the variable, the signature is added.
Sample script:
Please modify message in your script as follows.
var signature = "\nsample signature"; // Added
var message = {
to: "someone#somewhere.com",
subject: sheetName,
body: "Hi team,\n\nPlease find attached the quote that you requested.\n" + result.getResponseText() + "\nThank you,\nMe" + signature, // Modified
name: "My Name",
attachments: [SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("Quote")]
}
Pattern 2:
In this pattern, by retrieving the sigunature of Gmail, the signature is added.
Sample script:
In this sample, Gmail API is used. So, before you use this script, please enable Gmail API at Advanced Google services. And, please modify message in your script as follows.
var signature = "<br>" + Gmail.Users.Settings.SendAs.list("me").sendAs[0].signature; // Added
var message = {
to: "someone#somewhere.com",
subject: sheetName,
htmlBody: ("Hi team,\n\nPlease find attached the quote that you requested.\n" + result.getResponseText() + "\nThank you,\nMe").replace(/\n/g, "<br>") + signature, // Added
name: "My Name",
attachments: [SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("Quote")]
}
The signature retrieved from Gmail is HTML. So in this pattern, htmlBody is used instead of body.
References:
Method: users.settings.sendAs.list

NetSuite SuiteScript 2.0 - Attach File Object to Email Being Sent Via SuiteScript

I am writing a script where I am trying to print a transaction and then email it. I keep getting the following error.
"Wrong parameter type: options.attachments is expected as file.File[]."
I can't tell what is wrong with my code. Here is the snipped of code that is causing the issues. The email sends just fine if I don't include the attachments parameter. Any help would be greatly appreciated.
var recID = 1213;
var userID = 1478;
var emailSender = 1478;
var emailSubject = "Test Email";
var emailBody = "This is a test.";
var mainRecipient = "test#test.com";
var additionalRecipients = "";
var recPDF = render.transaction({
entityId: recID,
printMode: render.PrintMode.PDF,
});
email.send({
author: author,
recipients: mainRecipient,
subject: emailSubject,
cc: additionalRecipients,
body: emailBody,
attachments: [recPDF],
relatedRecords: {
transactionId: recID
}
});
Figured out my issue. There was a conflict attachment for some reason with the library file I had attached to the Suitelet running the script. By removing the library file, it resolved the issue.

how to post attachments using Upload Collection - pending

I am trying to use the same code wrt official upload collection pending
and in controller where upload is called :
onStartUpload: function(oEvent) {
var oUploadCollection = this.byId("UploadCollection");
var cFiles = oUploadCollection.getItems().length;
var uploadInfo = cFiles + " file(s)";
if (cFiles > 0) {
oUploadCollection.upload();
MessageBox.information("Uploaded " + uploadInfo);
}
},
I have set all required header parameters in onChange as:
onChange: function(oEvent) {
var oUploadCollection = oEvent.getSource();
// Header Token
var oCustomerHeaderEmailToken = new UploadCollectionParameter({
name: "xxxx",
value: xxxxx
});
// Header Token
var oCustomerHeaderAuthToken = new UploadCollectionParameter({
name: "xxxx",
value: "xxxx"
});
oUploadCollection.addHeaderParameter(oCustomerHeaderEmailToken);
oUploadCollection.addHeaderParameter(oCustomerHeaderAuthToken);
},
When i tried uploading in BE it gave me error as :
current request is not a multipart request
Then I tried adding to onChange :
var oCustomerHeaderContentType = new UploadCollectionParameter({
name: "Content-Type",
value: "multipart/form-data; boundary=----WebKitFormBoundarycXEQN6de4OdX0FBe"
});
oUploadCollection.addHeaderParameter(oCustomerHeaderContentType);
It didn't work even though the error is gone ,
The API works fine and tested in postman but why not with upload collection ? May i know the request sent is a multipart form-data ? Do I need to add any extra parameters ?
How does a simple back end API (if JAVA/Python) would be to collect files from when upload collection is used ? as there is no name to refer in server side like fileuploader and if the request is a multipart in upload collection
hope the experts help me out with this ... thanks :)

Google Form Responses in a Notification Email

I'm using the Form Notifications add-on in a Google Form. I've edited the Code.gs and CreatorNotification.html files and all works fine - when a Google Form is submitted I get an email. Now I'm trying to get some of the fields from that Form submission into the email. But with the edits I've added below, the email notification stops working.
In the Code.gs script I have:
function sendCreatorNotification() {
var form = FormApp.getActiveForm();
var settings = PropertiesService.getDocumentProperties();
var responseStep = settings.getProperty('responseStep');
responseStep = responseStep ? parseInt(responseStep) : 10;
function onFormSubmit(e) {
//Get information from form and set as variables
var First_Name = e.value[2];
// If the total number of form responses is an even multiple of the
// response step setting, send a notification email(s) to the form
// creator(s). For example, if the response step is 10, notifications
// will be sent when there are 10, 20, 30, etc. total form responses
// received.
if (form.getResponses().length % responseStep == 0) {
var addresses = settings.getProperty('creatorEmail').split(',');
if (MailApp.getRemainingDailyQuota() > addresses.length) {
var template = HtmlService.createTemplateFromFile('CreatorNotification');
template.summary = form.getSummaryUrl();
template.responses = form.getResponses().length;
template.title = form.getTitle();
template.responseStep = responseStep;
template.formUrl = form.getEditUrl();
template.notice = NOTICE;
template.firstname = First_Name;
var message = template.evaluate();
MailApp.sendEmail(settings.getProperty('creatorEmail'),
form.getTitle() + ': Case submission',
message.getContent(), {
name: ADDON_TITLE,
htmlBody: message.getContent()
});
}
}
}
}
In the CreatorNotification.html I have:
<p><i>Form Notifications</i> (a Google Forms add-on) has detected that the form
titled <b><?= title ?></b> has received
<?= responses ?> responses so far.</p>
<p>Summary of form responses</p>
<p>First Name:</p> <?= firstname ?>
Any direction would be appreciated.
You are trying to run two triggers. That "Add-on" code creates a trigger. The Add-on creates an "Installable" trigger. You already have one trigger set up for the form being submitted. The onFormSubmit(e) function is a "Simple" trigger. So, you have two triggers set up to run when a form is submitted. So, you created a conflict. If you look in the RESOURCES menu, under CURRENT PROJECT's TRIGGERS, you should see a trigger defined for the sendCreatorNotification() function.
Here's what you can try. You don't need a seperate onFormSubmit(e) simple trigger. The sendCreatorNotification() function, has the event object available to it. Just add e to the sendCreatorNotification() function:
sendCreatorNotification(e)
The write your code to get the value out of e.