Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Last active October 1, 2021 17:52
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sturmenta/212078e73293ad1e27bdf0a4b4e09403 to your computer and use it in GitHub Desktop.
Save sturmenta/212078e73293ad1e27bdf0a4b4e09403 to your computer and use it in GitHub Desktop.
Firebase Functions Send Mail

Send mails from firebase using nodemailer and firestore

FIREBASE FUNCTIONS CONFIG

https://firebase.google.com/docs/functions/config-env?hl=es-419

Set config

firebase functions:config:set gmail.email='someEmail' gmail.password='somePass'

Get config

firebase functions:config:get

Or

const functions = require('firebase-functions');

console.log(functions.config().gmail.email);
console.log(functions.config().gmail.password);
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const sendMail = require('./mail');
admin.initializeApp(functions.config().firebase);
exports.sendMail = functions.firestore
.document('mails/{mailId}')
.onCreate(snap => {
const { destination, title, body, html } = snap.data();
return sendMail({
destination,
//
title,
body,
html,
})
.then(res => console.log(res))
.catch(err => console.log(err));
});
'use strict';
//If you use gmail (recommended option)
// Allow access to your google account from this link https://accounts.google.com/b/0/DisplayUnlockCaptcha
// And allow access for less secure applications https://myaccount.google.com/lesssecureapps
const nodemailer = require('nodemailer');
const functions = require('firebase-functions');
exports = module.exports = ({
senderName = 'AppName',
destination,
//
title = 'Default title',
body = 'Default body',
html = null,
user = functions.config().gmail.email,
pass = functions.config().gmail.password,
}) => {
return new Promise((resolve, reject) => {
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: { user, pass }
});
transporter.sendMail({
from: `${senderName} ${user}`,
to: destination,
subject: title,
html: html || `<p>${body}</p>`
}, (err, res) => {
if (err) reject(err);
else resolve(res);
transporter.close();
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment