Right now the main issue is that it is not recognizing the birthdays and labeling them as invalid. So it is not sending the emails. This is from google sheets to google appscripts.
In the spread sheet i have emails in column H
The birthdate in column E
And the name of the recipient in column B
It starts on the third line so the first name would be on B3, email on H3, birthdate on E3
this is the code I have so far:
function createBirthdayEmailTrigger() {
// Delete all existing triggers for the current project to avoid duplicates
var triggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < triggers.length; i++) {
ScriptApp.deleteTrigger(triggers[i]);
}
// Create a new time-based trigger to run every day at 10 AM
ScriptApp.newTrigger("sendBirthdayEmails")
.timeBased()
.everyDays(1)
.atHour(9)
.nearMinute(11)
.create();
Logger.log('Trigger created to run at 10 AM every day.');
}
function sendBirthdayEmails() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CLIENTS HEALTH");
if (!sheet) {
Logger.log('Sheet not found.');
return;
}
var lastRow = sheet.getLastRow();
var range = sheet.getRange("B3:S" + lastRow);
var data = range.getValues();
// Set timezone and get today's date
var timezone = "America/New_York";
var today = Utilities.formatDate(new Date(), timezone, "MM-dd");
Logger.log('Today's Date: ' + today);
// Iterate over each row in the sheet
for (var i = 0; i < data.length; i++) {
var name = data[i][0];
var email = data[i][7]; // Assuming email is in column H
var birthDateStr = data[i][4]; // Assuming birth date is in column E
// Check if birthDate is a valid date
var birthDate = new Date(birthDateStr);
if (isNaN(birthDate.getTime())) {
Logger.log('Invalid birth date for client: ' + name + ' - ' + birthDateStr);
continue;
}
// Format birthDate to MM-dd
var birthDateFormatted = Utilities.formatDate(birthDate, timezone, "MM-dd");
Logger.log('Checking client: ' + name + ' with birthday: ' + birthDateFormatted);
// Check if the formatted birth date matches today's date
if (birthDateFormatted === today && email && email.includes("@")) {
Logger.log('Sending birthday email to: ' + email);
var subject = "Happy Birthday";
var body = `
<img src="https://drive.google.com/uc?export=view&id=1QcsC_sqhl8Nt7BgNy98GdQisFygvkzW4" alt="Birthday Image" style="width:900px;height:600px;display:block;margin:auto;">
<p style="font-family: 'Brush Script MT', cursive, Arial, sans-serif; font-size: 42px; color: red; text-align: center;">
Happy Birthday, 🎂🎂 ${name} 🎈🎈!
</p>
;
try {
MailApp.sendEmail({
to: email.trim(),
subject: subject,
htmlBody: body
});
Logger.log('Email successfully sent to: ' + email);
} catch (e) {
Logger.log('Failed to send email to: ' + email + ' - ' + e.message);
}
} else {
Logger.log('No birthday match or invalid email for: ' + name);
}
}
}
`
AmateurCoder is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.