I want to send an email with Google Script, but I need to use the public (group) mailbox,
I didn't find an example of sending email from the group account on the Google API, and I couldn't find the answer on the stack overflow. Could you please tell me if there is a method that use google script send email with group account?
I have solved the problem.
from "Account and import" add your group account then You can reference below code to test whether you can send an email in group account.
var alias = GmailApp.getAliases();
var num = alias.length-1;
var myMail = getMyMail();
if (num<0){
return false
}else{
for (var i = 0;i <= num;i++){
if (alias[i] == "yourGroup#Domain.com"){
var myGroupMail=alias[i];
break;
}
}
}
if (myGroupMail != "yourGroup#Domain.com"){return false}
GmailApp.sendEmail(toEmail,strSubject,strContent,{from : myGroupMail});
Related
I'm trying to use Google Script to extract email address and name from forwarded emails that I've filed under a specific label.
The emails look like this:
From: Person A
Sent: Sunday, September 22, 2019 8:00 PM
To: Other, Email
Subject: Forwarded Email
BODY
They have all have been forwarded to this specific inbox. Therefore the headers actually include my other email address I forwarded from.
I've sorted over 2000 emails and now for each of the labels I want to extract the name of the sender (Person A) and their email address (person#gmail.com) in a spreadsheet. Preferably, I can have the first and last name in separate cells (e.g. Person | A | email address)
The code I have thus far is below:
function processInboxToSheet() {
// Have to get data separate to avoid google app script limit!
var start = 0;
var label = GmailApp.getUserLabelByName("LABEL");
var threads = label.getThreads();
var sheet = SpreadsheetApp.getActiveSheet();
var result = [];
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
var content = messages[0].getPlainBody();
// implement your own parsing rule inside
if (content) {
var tmp;
tmp = content.match(/From:\n([A-Za-z0-9\s]+)(\r?\n)/);
var name = (tmp && tmp[1]) ? tmp[1].trim() : 'No name';
tmp = content.match(/<\n([A-Za-z0-9#.]+)/);
var email = (tmp && tmp[1]) ? tmp[1].trim() : 'No email';
sheet.appendRow([name, email]);
Utilities.sleep(500);
}
}
};
I only get No name and No email as output so something is not quite working in the code. I would appreciate your help.
You are parsing the plain body, it doesn’t contain to and from. It only contains the message body. The API has methods getTo() and getFrom() that contains what you want to parse. See the API for GmailMessage for more details.
So I have a Google sheet that collects registration data from customers. Included in the data collected is a student's name, the session the student elected to attend and a credit card number. Once a submission has been made, I get a notification. Upon notification, I go to my Google sheet and charge the credit card the appropriate amount.
Once the credit card has been charged, I then want to generate a confirmation email to the customer that includes the student's name, the session the student registered to attend and the amount charged to the credit card. My code seems to work fine except when it comes to replacing curly bracket placeholders in my "template text" (i.e., {Name},{sessions} and {ChargeAmount} with the actual values which I've defined as variables.
Note: When I just replace {StudentName} with text like "Joe" it works. However, {Sessions} does not get replaced and neither does {ChargeAmount}. I think this is a syntax error.
Here's what I really want to happen but can't get to work:
var emailText = templateText.replace("{Name}",studentName);templateText.replace("{Sessions}",sessionName);templateText.replace("{ChargeAmount}",ChgAmt);
function SendEmail() {
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("B2");
var studentRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("C2");
var studentName = studentRange.getValues();
var sessionRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("D2");
var sessionName = sessionRange.getValues();
var emailAddress = emailRange.getValues();
var ChgAmt = Browser.inputBox("Charge Amount");
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1,1).getValue();
// NOTE! What I really want to do is replace {Name} with the var "studentName"... not the text "Joe", {Sessions} with the var "sessionName" and {ChargeAmount} with the var "ChgAmt". I can't this to work either! STRUGGLING!!!
var emailText = templateText.replace("{StudentName}","Joe");templateText.replace("{Sessions}","May - Session#1");templateText.replace("{ChargeAmount}","$500");
// Send Alert Email.
var subject = 'Junior Golf Clinic Registration Receipt';
var message = emailText;
MailApp.sendEmail(emailAddress, subject, message);
}
Here's the result of my existing code which does not properly pull in the values I need.
useremail#gmail.com
9:18 AM (37 minutes ago)
to me
This is the email body.
This is the amount charged to credit card {ChargeAmount}. [Not right. This should be the actual value represented by the var "ChgAmt"]
This is the student's name: Joe [this seems to work when I replace the placeholder {Name} with text like "Joe" but not when I try to replace the placeholder {Name} with the var "studentName"]
These are the sessions the student is scheduled to attend: {Sessions}
[Not right. This should be the actual sessions represented by the var "sessionName"]
Here's more information about the clinics themselves.
This line is incorrect, you're never actually storing your other replace statements.
var emailText = templateText.replace("{StudentName}","Joe");templateText.replace("{Sessions}","May - Session#1");templateText.replace("{ChargeAmount}","$500");
It should be:
var emailText = templateText.replace("{StudentName}","Joe").replace("{Sessions}","May - Session#1").replace("{ChargeAmount}","$500");
As jmcgriz notes, the problem is with the separate calls to .replace. Chaining them fixes your issue.
Here is some dummy code showing what that might look like:
function SendEmail() {
// fetch these values as you need
var studentName = 'Joe'
var sessionName = "May - Session#1";
var emailAddress = 'joe#joe.com'
var chargeAmt = "$500";
// This is what needed to change
var emailText = templateText
.replace("{StudentName}", studentName)
.replace("{Sessions}", sessionName)
.replace("{ChargeAmount}", chargeAmt);
var subject = 'Junior Golf Clinic Registration Receipt';
var message = emailText;
MailApp.sendEmail(emailAddress, subject, message);
}
SendEmail()
<script>
// Mocking MailApp for testing
const MailApp = {
sendEmail: (addr, subj, mess) =>
console.log(`Sending "${addr}" email "${subj}"\n\n${mess}`)
}
const templateText = `
This is the email body.
This is the amount charged to credit card {ChargeAmount}.
This is the student's name: {StudentName}
These are the sessions the student is scheduled to attend: {Sessions}
Here's more information about the clinics themselves.`
</script>
Maybe the subject line is incorrect, but here is my question:
I am trying to see if the user input is a valid email address, or if there is an input at all at the first place. if none of the above, then i want to loop the question requesting the answer again, until i get a valid answer(in this case, email address). Below is the code i have written, which was working until i added REGEX testing.
function emailPrompt() {
var ui = SpreadsheetApp.getUi();
var entry = ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
var button = entry.getSelectedButton();
var response = entry.getResponseText();
var sum = 1;
for(var i=0;i<sum;i++){
var regex = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var matchRegex = regex.test(response);
if(response == ""||response == " "|| response != matchRegex) {
if(!matchRegex) { ui.alert("Invalid Email Address")}
ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
sum++;
} else {
sum--;
}
}
return response;
Logger.log(response);
}
Specifically, if the input is incorrect/invalid email address, i inserted another if statement to alert the user. I am positive i am messed the code somewhere in the REGEX matching/testing. Any help would be much appreciated. TIA
Your regex statement is ok. It tests and returns a boolean. Your first if statement is a little redundant. response == ""||response == " "|| response != matchRegex Most of these are already tested by the regex statement and the last one should never be false as you are comparing a string to a boolean.
EDIT: Additionally, the response variable is never update with the new prompt data (Code updated).
function emailPrompt() {
var ui = SpreadsheetApp.getUi();
var entry = ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
var button = entry.getSelectedButton();
var response = entry.getResponseText();
var sum = 1;
for(var i=0;i<sum;i++){
var regex = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var matchRegex = regex.test(response);
if(!matchRegex) {
ui.alert("Invalid Email Address");
//Ask for email again and set new response.
var responseItem = ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
response = responseItem.getResponseText();
sum++;
}
//sum--; this isn't needed to stop the loop.
if(sum > 3) //You shouldn't go on forever... Stop after a few tries?
break;
}
Logger.log(response); //Moved above return so this code runs.
return response;
}
Problem : I have got list of 1000 recipients, but I want to sent mail in batch of 200 each. I am using node js module emailjs for sending mail.
Below is my snippet of code.
// Code goes here
var sizeLimit = 200;
var totalData = 350;
var cycles = Math.ceil(totalData / sizeLimit);
var start;
var end;
var recepients = "a#gmail.com,b#gmail.com...long list"
for (var i = 0; i < cycles; i++) {
start = end ? end + 1 : 0
end = (sizeLimit) * (i + 1) > totalData ? (totalData - start) + start :
(sizeLimit) * (i + 1)
var bcc = recepients.substr(start,end);
(function(i) {
setTimeout(function() {
console.log(i)
//Sending mail using emailjs
//bcc
}, i * 5000)
})(i)
}
What is the best way of sending mail in batches, I don't want to use Redis.
From what I can gather, you are attempting to send email batches by putting 200 recipients into the BCC field at once. This is extremely bad practice and shows a lack of understanding of the fundamentals of what you're trying to do.
What you should be doing instead is sending one email to one recipient at a time. This is what mailing list software does anyway and is what you should use for this purpose anyway instead of trying to roll your own.
You can use SaaS offerings like MailChimp, open source solutions like Mailtrain or my personal favorite Sendy, which features API access, so you can automate certain aspects.
I have client side email validation script Javascript+RegEx, it works fine, but I want to exclude certain domains while validating, namely all Apple domains since they do not work (emails sent to these addresses are deleted without any notice): #apple.com, #me.com, #icloud.com, #mac.com.
I found appropriate questions here, but still they are not the same I am asking for help.
Please, help to implement this
Can it be done via RegEx modification, or I have to use loop and search substrings (#apple.com, #me.com, #icloud.com, #mac.com) after the main email validation is done?
function verifyMe(){
var msg='';
var email=document.getElementById('email').value;
if(!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) ||
document.getElementById('email').value=='')
{
msg+='- Invalid Email Address: '+email+'\n\n';
document.getElementById('Eemail').style.color='#ffffff';
}
else
document.getElementById('Eemail').style.color='#bbb'
if(msg!='')
return false;
else
{
search_code(); //it's ok go ahead
return true;
}
}
Both approaches would work.
For the regex one, just insert the following part after the # in the regex (negative lookahead):
(?!(?:apple|me|icloud|mac)\.com$)
But a better regex overall would be:
^\w+[-\.\w]*#(?!(?:apple|me|icloud|mac)\.com$)\w+[-\.\w]*?\.\w{2,4}$
For the other approach, the following should work:
function isValidMailAddress(email) {
var match = /^\w+[-\.\w]*#(\w+[-\.\w]*?\.\w{2,4})$/.exec(email);
if (!match)
return false;
var forbiddenDomains = ["apple.com", "me.com", "icloud.com", "mac.com"];
if (forbiddenDomains.indexOf(match[1].toLowerCase()) >= 0)
return false;
return true;
}
It's up to you to decide which approach you feel most comfortable with.
You can use jQuery.inArray() for checking email with a specific domain name.
var email ="abc#xyz.edu.au"
var str = email.split('#').slice(1);
var allowedDomains = ['xyz.edu.au','abc.edu.au'];
if($.inArray(str[0], allowedDomains) === -1) {
alert('email is allowed.');
}
else{
alert('email not allowed.');
}
I updated #Lucas answer to match any type of country domain (apple.com, apple.de etc.).
Moreover it should be more robust because its closer to W3C standard: https://emailregex.com/
^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#(?!(?:yahoo|gmail|icloud|web|googlemail|aol|zoho|protonmail|outlook|hotmail|gmx|mail)[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]{1,10}$)[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$