Can someone help me fix/improve this code to send automatic emails to clients for their birthdays

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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);
}
}
}
`
</code>
<code>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); } } } ` </code>
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);
    }
  }
}
`

New contributor

AmateurCoder is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật