9
votes

I m trying to send a test email to my email when anything is written in /emails but the email never gets sent and the function logs are empty.

exports.sendTestEmail = functions.database.ref('/emails')
  .onWrite(event => {
    return sendTestEmail('[email protected]');
  })
// [END onWrite]

// Sends a welcome email to the given user.
function sendTestEmail(email) {
  const mailOptions = {
    from: `${APP_NAME} <[email protected]>`,
    to: email
  };
  // The user subscribed to the newsletter.
  mailOptions.subject = `Welcome to ${APP_NAME}!`;
  mailOptions.text = `Hey there! Welcome to ${APP_NAME}. I hope you will enjoy our service.`;
  return mailTransport.sendMail(mailOptions).then(() => {
    console.log('New welcome email sent to:', email);
  });

}

Edit ***

The above code works. I was trying to trigger the function on emails while the correct name was email.

1
Are you using gmail as your smtp service? If you are, you may need to use an app password instead of your personal password due to Google's security. Here's a way to do that support.google.com/accounts/answer/185833?hl=en - Tobi Akerele
yes I am. the problem is that I send emails using the same format when users create accounts. and that works. - Ciprian
Try catching errors on the send: mailTransport.sendMail(mailOptions).then(...).catch(error => { console.error('Error sending:', error); }); - Bob Snyder
You say "the function logs are empty". You are seeing the entry that says Function execution started, right? - Bob Snyder
Also ensure that the value written to /emails is a change from the previous value. I haven't tested all the client SDKs, but with Android, performing a write to a location that does not change the value will not cause the onWrite() event to fire. - Bob Snyder

1 Answers

4
votes

Correct way of sending an email using Firebase Cloud Functions!

exports.sendTestEmail = functions.database.ref('/emails')
  .onWrite(event => {
    return sendTestEmail('[email protected]');
  })
// [END onWrite]

// Sends a welcome email to the given user.
function sendTestEmail(email) {
  const mailOptions = {
    from: `${APP_NAME} <[email protected]>`,
    to: email
  };
  // The user subscribed to the newsletter.
  mailOptions.subject = `Welcome to ${APP_NAME}!`;
  mailOptions.text = `Hey there! Welcome to ${APP_NAME}. I hope you will enjoy our service.`;
  return mailTransport.sendMail(mailOptions).then(() => {
    console.log('New welcome email sent to:', email);
  });

}