Skip to content

Instantly share code, notes, and snippets.

@alan89
Created October 15, 2019 01:50
Show Gist options
  • Save alan89/81b54ee697b8fb28f0a99bef0f94ee35 to your computer and use it in GitHub Desktop.
Save alan89/81b54ee697b8fb28f0a99bef0f94ee35 to your computer and use it in GitHub Desktop.
Cloud function to send custom emails using nodemailer and the Firebase adminSDK when a user is created
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const nodemailer = require('nodemailer');
// Configure the email transport using the default SMTP transport and a GMail account.
// For other types of transports such as Sendgrid see https://nodemailer.com/transports/
// TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables.
const gmailEmail = functions.config().google.email;
const gmailPassword = functions.config().google.password;
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: gmailEmail,
pass: gmailPassword,
},
});
// Sends an email confirmation when a user changes his mailing list subscription.
exports.sendVerificationEmail = functions
.auth
.user()
.onCreate((user) => {
const email = user.email; // The email of the user.
const displayName = user.displayName; // The display name of the user.
const actionCodeSettings = {
// URL you want to redirect back to. The domain (www.example.com) for
// this URL must be whitelisted in the Firebase Console.
url: '<YOUR URL>',
// This must be true for email link sign-in.
handleCodeInApp: false,
iOS: {
bundleId: '<YOUR BUNDLE ID>'
},
android: {
packageName: '<YOUR PACKAGE NAME>',
installApp: false,
minimumVersion: '12'
},
dynamicLinkDomain: '<DYNAMIC LINK>'
};
const mailOptions = {
from: '"New app Corp" <noreply@firebase.com>',
to: email,
};
admin.auth().generateEmailVerificationLink(email, actionCodeSettings)
.then(async (link) => {
// Construct email verification template, embed the link and send
// using custom SMTP server.
try {
// Building Email message.
mailOptions.subject = 'Thanks and Welcome!';
mailOptions.text = 'Thanks you for register to our app. This is the LINK TO VERIFY: \n' + link ;
await mailTransport.sendMail(mailOptions);
console.log(`New subscription confirmation email sent to:`, email);
} catch(error) {
console.error('There was an error while sending the email:', error);
}
return '200';
})
.catch((error) => {
console.error(error);
return '200';
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment