Prevent text wrapping using MailApp.sendEmail google sheets? google script - google-apps-script

I have the following working code to send an email based on the content of one cell. This cell contains the values of other cells to create the email.
The emails send to 2 recipients and it works fine.
However, upon receiving the email, the text is wrapped after 74 characters.
Sample sheet replicates issue:
https://docs.google.com/spreadsheets/d/1PDSHbrhxiJliTGNx2rlJRAJIrjITADVuGWqTuvpjrgw/edit?usp=sharing
How can i prevent the wrapping? I want the email to send as it appears in the 'body' cell:
=G2&char(10)&E9&char(10)&E10&char(10)&E11&char(10)&E12&char(10)&E13&char(10)&E14&char(10)&E15&char(10)&E16&char(10)&E17&char(10)&E18&char(10)&E19&char(10)&E20&char(10)&E21&char(10)&E22&char(10)&E23&char(10)&E24&char(10)&E25&char(10)&E26&char(10)&E27&char(10)&E28&char(10)&E29&char(10)&E30&char(10)&E31&char(10)
Send email function:
var EMAIL_SENT = 'EMAIL_SENT';
function SendEmailACC() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("EmailACC");
var startRow = 2;
var numRows = 2;
var dataRange = sheet.getRange(startRow, 1, numRows, 6);
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var subject = row[2];
var emailSent = row[5];
var EMAIL_SENT = "Email Processed";
var EMAIL_FAIL = "Email Not Sent";
if (emailSent !== EMAIL_SENT) {
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 5).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
Utilities.sleep(3000);// pause in the loop
DeleteStatus();
}
How Sample email should look:
Good Morning,
The following claim may have had an incorrect or missing ACC number or was not submitted by the referrer at time of request.
The claim has since been amended or submitted for the release of $50. Updated details are as below.
Vendor ID: ABC123
Invoice number: ABCDE12345
Service Date: 11/10/2019
Patient: John Smith
Service Code(s): COD88
First supplied ACC Number: BTT123
Exam Type: Exam Abc
Amended or updated ACC Number: COD123
Please let me know if any further information is required.
How the email actually comes out:
Good Morning,
The following claim may have had an incorrect or missing ACC number or was
not submitted by the referrer at time of request.
The claim has since been amended or submitted for the release of $50.
Updated details are as below.
Vendor ID: G0A368
Invoice number: ABCDE12345
Service Date: 11/10/2019
Patient: John Smith
Service Code(s): COD88
First supplied ACC Number: BTT123
Exam Type: Exam Abc
Amended or updated ACC Number: COD123
Please let me know if any further information is required.
Any suggestions appreciated

How about this answer? Please think of this as jut one of several possible answers.
Pattern 1:
In this pattern, Class GmailApp is used.
From:
MailApp.sendEmail(emailAddress, subject, message);
To:
GmailApp.sendEmail(emailAddress, subject, message);
Pattern 2:
In this pattern, Gmail API is used. In this case, please enable Gmail API at Advanced Google services.
From:
MailApp.sendEmail(emailAddress, subject, message);
To:
var raw = Utilities.base64EncodeWebSafe("Subject: " + subject + "\r\n" + "To: " + emailAddress + "\r\n" + "Content-Type: text/plain; charset=UTF-8\r\n\r\n" + message + "\r\n\r\n");
Gmail.Users.Messages.send({raw: raw}, "me");
If the characters which are more than the version of Unicode 6.0 are included in the email, Gmail API is required to be used. Please be careful this. Ref
Note:
In my experience, also I had the same issue. At that time, the issue could be resolved by using Class GmailApp. But unfortunately, I couldn't find the detail explanation about this at the official document. I apologize for this.
References:
MailApp.sendEmail(recipient, subject, body)
GmailApp.sendEmail(recipient, subject, body)
Advanced Google Services
Gmail API

Related

Google Sheets Send SMS to a specific person based on status change of a cell

If you are reading my question, Thank you for taking the time out of your day to help.
Background:
I have a form that my field techs use in order to request parts, I would like to keep them updated on the status of a part order with an automated sms text to their phone.
Specifics:
Link to test Sheet
https://docs.google.com/spreadsheets/d/1hEDEk-3-z3Wh6PNLoY6PgmbSJZ7OcdMR0kFCl0BRrYU/edit?usp=sharing
Parts Request (Picture)
Status Change
When a Status is changed in (column G), this will trigger an SMS to be sent.
Recipient
The SMS will be sent to the Team Lead ( Column B) in that row.
Example: Status is changed (G2), SMS is sent to Team Lead (B2).
Employee Info (Picture)
Employee Information:
The Script pulls the Employee Telephone number(Employee Info! B2) from the Employee Info Sheet
Text Body:
The Message that is sent would be the entire row in the text message
-Team Lead
-Type of Request
-Job Name
-Part Description
-QTY Missing
-Status
The Script i have tried so far has been a simple one, based on a trigger of anytime a change is made to the sheet. Here is what i have used so far, this has worked and has been sending generic texts. Any Help would be greatly appreciated.
function sendText() {
var EmailTo = "'Mobile Number'"#txt.att.net";
var subject = "Whatever";
var body = "Text";
MailApp.sendEmail(EmailTo, subject, body);
}
The processes needed to achieve your goal involves fetching the desired details on the row wherein the status of the request changes, incorporating the given phone number to the appropriate carrier domain, and adding an installable trigger so that the script will automatically work when there are changes to the Status Column.
Here is the script:
function sendUpdates(e) {
var ss = e.source;
var shEmployeeInfo = ss.getSheetByName("Parts Request");
var shPartsRequest = ss.getSheetByName("Employee Info");
var row = e.range.getRow();
var column = e.range.getColumn();
if(column == 7) { //To limit checking of changes to the Status column
var info = shEmployeeInfo.getRange(row, 2, 1, 6).getValues();
var header = shEmployeeInfo.getRange(1, 2, 1, 6).getValues();
var carrier = shPartsRequest.getRange(row,4).getValues();
const subject = "Insert Subject Here."; //Edit this to change the subject
const carrierMap = { "ATT": 'txt.att.net',
"T-Mobile": 'tmomail.net',
"Sprint": 'messaging.sprintpcs.com',
"Verizon": 'vtext.com',
"Cricket": 'mms.mycricket.com' }
var phoneNumber = shPartsRequest.getRange(row,2).getValues();
var emailTo = `${phoneNumber}#${carrierMap[carrier]}`;
var body = "";
for(let i = 0; i <= 5; i++) {
body += header[0][i] + ": " + info[0][i] + "\n";
}
MailApp.sendEmail(emailTo, subject, body);
}
}
The installable trigger should be set as:
Please refer to the Installable Triggers Guide for more information.
As for the result, I made a test case and got this:

Weird behaviour of Mailapp.sendEmail in Google apps script

I have been sending emails successfully through Google apps script triggered through submission in a Google sheet. Lately (about a week back), the email sender starts behaving very weird.
If I use the following format, my emails get bounced
MailApp.sendEmail(email1, subject, message,{cc:email2,attachments:[file.next()]});
If I use the following form, the email does NOT get delivered neither does it get bounced
MailApp.sendEmail(email, subject, message);
If I use the following format, the recipient gets the message as shown
MailApp.sendEmail(email,subject,{htmlBody: message});
Revecied message
[object Object]
and the rest of the stuff blank!
I'm at my wits' end as to how to go about. Any help or a pointer will be of immense help. Regards
Madhurjya
Following is the app script, which is attached to the Google sheet. Once I run the function sendPasswd() from sheet, it gets some vital parameters from the sheet data and then send the message to the person (through the variable email2)
function sendPasswd() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var dataRange = sheet.getDataRange()
var data = dataRange.getValues();
var subject = "Example Subject";
var message = "";
var i;
var file = DriveApp.getFilesByName("some_file.pdf");
for (i in data) {
var row = data[i];
if (i == 0) continue; // Skip the first row
if (row[4] == "Sent") continue;
var first = row[0]; var last = row[1]; var email = row[2];
var passwd = row[3]; var email2 = row[7];
if (row[15] == "some condition") {
message = "Dear <b>"+first+" "+last+"</b>,<br><br>"+
"This is to inform you that your .... ";
MailApp.sendEmail(email2, subject, message);
//MailApp.sendEmail(email2,subject,{htmlBody: "message"});
//MailApp.sendEmail(email2, subject, message,{cc:"some_email#example.com",attachments:[file.next()]});
}
}
}
The surprising fact is that from the same account similar emails are being sent and are NOT affected!
Madhurjya
This might be happening because you're using htmlbody which is part of options as third argument whereas in sendEmail(recipient, subject, body, options) of class MailApp, body should be third argument, that's is the reason of getting [object Object].
Try following modification:-
MailApp.sendEmail(email2,subject,"",{htmlBody: message});
Reference:
sendEmail
You could also use this way (its really more practical):
const email 'yourEmail#outlook.com'
const cc ='copyEmail#hotmail.com'
const bcc = 'blindCarbonCopy#gmail.com'
MailApp.sendEmail({
to:email,
cc: cc,
bcc: bcc,
subject: 'Whatever you want, even template strings' ,
htmlBody: `
You could just create your HTML IN HERE (using template strings)
Or create before and add here as variable as well.
`
})

Google Sheet - Send Email

I need my google sheet to send emails every time a condition becomes true.
In this case, every time value of C2 is lower than value of J2.
On the cell L2 there is the email address.
The code (found online and just edited)
function CheckPrice() {
var LastPriceRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("C2");
var LastPrice = LastPriceRange.getValue();
var EntryLimitRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("J2");
var EntryLimit = LastPriceRange.getValue();
var StockNameRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("B2");
var StockName = LastPriceRange.getValue();
// Check totals sales
if (LastPrice < EntryLimit){
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("L2");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = 'Ticker ' + StockName + ' has triggered the alert';
var subject = 'Stock Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
}
With this code I don't receive any error, but I don't even receive the email.
I granted permissions as requested when I run the script for the first time.
On L2 I put the same email address I granted permission (I send email to myself).
I did a try even putting a secondary email address I have.
Can you please show me what's wrong ?
Issues:
See the first lines of your code where you define LastPrice,
EntryLimit and StockName. All of them are coming from the same
range: LastPriceRange.
I also removed all the unnecessary calls in your script. There is no
need to call
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts") so
many times when you can just put it in a variable and use that
variable instead.
Also, you don't need to define unnecessary
variables. For example, you can get the value of a cell with one line:
sh.getRange("B2").getValue().
Solution:
function CheckPrice() {
const sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts");
const LastPrice = sh.getRange("C2").getValue();
const EntryLimit = sh.getRange("J2").getValue();
const StockName = sh.getRange("B2").getValue();
// Check totals sales
if (LastPrice < EntryLimit){
// Fetch the email address
const emailAddress = sh.getRange("L2").getValue();
// Send Alert Email.
const message = 'Ticker ' + StockName + ' has triggered the alert';
const subject = 'Stock Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
}
If you want an email to be sent when you edit a particular cell, then you need to transform the aforementioned solution to an onEdit(e) trigger. If you want a time basis trigger then you can just use the solution above directly.

Auto-direct emails to specific addresses on Google Form submit

This is my first post so apologies in advance if I am posting to the wrong place or asking a question that has been answered elsewhere - go easy on me!
In a nutshell, I have a Google Form and a connected Google Sheet. I need to automate it so that, when a new form is submitted, an email is sent to a specific colleague (the student's supervisor). I have had a good go myself but am now totally stuck!
I have created the form, linked it to a sheet, written the code, added the trigger and tested by submitting a form. Nothing happened! No error messages, just... nothing!
Any advice hugely appreciated. I am very new to this and still taking baby steps.
The code I have cobbled together (which is probably full of errors!) is as follows:
function wa132657(e) {
//setup the spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
//get the range from OnFormSubmit
var range = e.range;
Logger.log("DEBUG: the range is "+range.getA1Notation());//DEBUG
// get the data for the range
var response = row.getValues();
// get the supervisor name from the form submission
var supervisor = response[0][1];
Logger.log("DEBUG: Supervisor = "+supervisor);// DEBUG
// get the emails list
var emailSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SupEmails");
// get ALL the data from this sheet
var emaildata = emailSheet.getDataRange().getValues();
// check how many rows of data
var emailLastRow = emailSheet.getLastRow();
// start the loop through the emails data
for (var i=1; i<emailLastRow; i++){
// if the supervisor is equal to SupervisorEmail
if (supervisor == emaildata[i][0]){
// there is a match
//Next, get the email address
var emailSupervisor = emaildata[i][1];
Logger.log("DEBUG: supervisor = "+emaildata[i][0]+", email address: "+emailSupervisor);// DEBUG
// Finally, send the Email.
var theirName = e.values[2];
var theirProgramme = e.values[3];
var theAbsenceReason = e.values[8];
var theAbsenceStart = e.values[5];
var theAbsenceEnd = e.values[6];
var subject = "Student Absence Report";
var message = "New Absence Report: " + theirName + " \n Programme: " + theirProgramme; + " \n\n
Reason for Absence: \n" + theAbsenceReason + " \n Start of Absence" + theAbsenceStart + "\n End of Absence:" + theAbsenceEnd;
MailApp.sendEmail(emailSupervisor, subject, message);
}
}
}

Custom Email based on Cell values in google sheets

I need help while building a Request Approval Flow in google Forms/Sheets
I have a data response sheet similar to like below, Column A to J headers are
"Timestamp" "EmailAddress" "Name" "Targets" "Account#" "Reason" "Access(Days)" "Approver" "Approved" "CaseID"
I have already setup a form submit email trigger to Approval body through formMule AddOn, Now I want to trigger email when Approval body approve or disapprove the request in Data response sheet.
Everytime when anyone select "Y" or "N" to column "I", script should suppose to trigger an email based on the data present in that row.
I am not an expert but tried to do it with following script and unfortunately not getting desired outcome, I set it up Current project trigger to OnEdit
function sendNotification1(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form Responses 1");
if(e.range.getColumn() == 9 && e.value == "Y")
{
var name = e.range.offset(0,-6).getValue();
var comment = e.range.offset(0,-3).getValue();
var email = e.range.offset(0,-7).getValue();
var case1 = e.range.offset(0,1).getValue();
var approver1 = e.range.offset(0,-1).getValue();
var subject = "Request has been Approved";
var body = "Hi " + name + ", your Change Request number " + case1 + " has been approved by " + approver1 + " with following comments: " + "\n\r" + comment;
MailApp.sendEmail(email, subject, body);
}
if(e.range.getColumn() == 9 && e.value == "N")
{
var name = e.range.offset(0,-6).getValue();
var comment = e.range.offset(0,-3).getValue();
var email = e.range.offset(0,-7).getValue();
var case1 = e.range.offset(0,1).getValue();
var approver1 = e.range.offset(0,-1).getValue();
var subject = "Request has been Disapproved";
var body = "Hi " + name + ", your Change Request number " + case1 + " has been Dis-Approved by " + approver1 + " with following comments: " + "\n\r" + comment;
MailApp.sendEmail(email, subject, body);
}
}
StackDriver logging showed the following error, but couldn't identify where the issue exist while referring the cell addresses.
2018-09-14 08:19:06.336 PKT
The coordinates or dimensions of the range are invalid. at sendNotification1(Code:6)
I am able to trigger an email on any edit event with following code, but no luck with conditional edit event trigger.
function sendNotification1(e) {
MailApp.sendEmail("myemail#companygmail.com", "Sample subject", "Sample body");
}
While debugging the code, I can see the following error
TypeError: Cannot read property "range" from undefined. (line 6, file "Code")
Any help will be highly appreciated
You are likely running into the issue of the code not knowing what range you are referring to, because you never tell it where to look.
Add the following to the top of the function:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("YOUR SHEET NAME");
And it should work perfectly.
EDIT: Here's the email I sent to myself when I tested it.