Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send email in Firebase for free?

I'm aware that Firebase doesn't allow you to send emails using 3rd party email services. So the only way is to send through Gmail.

So I searched the internet for ways, so here's a snippet that works and allows me to send email without cost.

export const shareSpeechWithEmail = functions.firestore
  .document("/sharedSpeeches/{userId}")
  .onCreate(async (snapshot, context) => {
    // const userId = context.params.userId;
    // const data = snapshot.data();
    const mailTransport = nodemailer.createTransport(
      `smtps://${process.env.USER_EMAIL}:${process.env.USER_PASSWORD}@smtp.gmail.com`
    );


    const mailOptions = {
      to: "[email protected]",
      subject: `Message test`,
      html: `<p><b>test</b></p>`
    };
    try {
      return mailTransport.sendMail(mailOptions);
    } catch (err) {
      console.log(err);
      return Promise.reject(err);
    }
  });

I want to create a template, so I used this package called email-templates for nodemailer. But the function doesn't get executed in Firebase Console and it doesn't show an error and shows a warning related to "billing".

export const shareSpeechWithEmail = functions.firestore
  .document("/sharedSpeeches/{userId}")
  .onCreate(async (snapshot, context) => {

    const email = new Email({
      send: true,
      preview: false,
      views: {
        root: path.resolve(__dirname, "../../src/emails")
        // root: path.resolve(__dirname, "emails")
      },
      message: {
        // from: "<[email protected]>"
        from: process.env.USER_EMAIL
      },
      transport: {
        secure: false,
        host: "smtp.gmail.com",
        port: 465,
        auth: {
          user: process.env.USER_EMAIL,
          pass: process.env.USER_PASSWORD
        }
      }
    });

    try {
      return email.send({
        template: "sharedSpeech",
        message: {
          to: "[email protected]",
          subject: "message test"
        },
        locals: {
          toUser: "testuser1",
          fromUser: "testuser2",
          title: "Speech 1",
          body: "<p>test using email <b>templates</b></p>"
        }
      });
    } catch (err) {
      console.log(err);
      return Promise.reject(err);
    }
  });
like image 702
The.Wolfgang.Grimmer Avatar asked Nov 19 '19 12:11

The.Wolfgang.Grimmer


People also ask

Is Firebase email free?

Billing. You will be charged a small amount (typically around $0.01/month) for the Firebase resources required by this extension (even if it is not used).

Can we send emails through Firebase?

The Trigger Email extension ( firestore-send-email ) lets you automatically send emails based on documents in a Cloud Firestore collection. Adding a document to the collection triggers this extension to send an email built from the document's fields.

How do I use Firebase SMTP?

You can set a custom SMTP server in the Firebase Authentication console. You don't need a custom domain for this. All you need to know is the SMTP host and port of SMTP2GO (something like mail.smtp2go.com and 587 ), and your account details from them (the username/password you use to log into smtp2go with).


4 Answers

you can send emails by using nodemailer:

npm install nodemailer cors

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
const cors = require('cors')({origin: true});
admin.initializeApp();

/**
* Here we're using Gmail to send 
*/
let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '[email protected]',
        pass: 'yourgmailaccpassword'
    }
});

exports.sendMail = functions.https.onRequest((req, res) => {
    cors(req, res, () => {

        // getting dest email by query string
        const dest = req.query.dest;

        const mailOptions = {
            from: 'Your Account Name <[email protected]>', // Something like: Jane Doe <[email protected]>
            to: dest,
            subject: 'test', // email subject
            html: `<p style="font-size: 16px;">test it!!</p>
                <br />
            ` // email content in HTML
        };

        // returning result
        return transporter.sendMail(mailOptions, (erro, info) => {
            if(erro){
                return res.send(erro.toString());
            }
            return res.send('Sended');
        });
    });    
});

See also here

Set Security-Level to avoid error-messages: Go to : https://www.google.com/settings/security/lesssecureapps set the Access for less secure apps setting to Enable

Refer to

like image 187
Micha Avatar answered Oct 21 '22 03:10

Micha


You can definitely send emails using third party services and Cloud Functions, as long as your project is on the Blaze plan. The official provided samples even suggest that "if switching to Sendgrid, Mailjet or Mailgun make sure you enable billing on your Firebase project as this is required to send requests to non-Google services."

https://github.com/firebase/functions-samples/tree/master/quickstarts/email-users

The key here, no matter which email system you're using, is that you really need to upgrade to the Blaze plan in order to make outgoing connections.

like image 35
Doug Stevenson Avatar answered Oct 21 '22 03:10

Doug Stevenson


Call a sendMail() cloud function directly via functions.https.onCall(..) :

As @Micha mentions don't forget to enable Less Secure Apps for the outgoing email: https://www.google.com/settings/security/lesssecureapps

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

let mailTransport = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '[email protected]',
        pass: '11112222'
    }
});

exports.sendMail = functions.https.onCall((data, context) => {

    console.log('enter exports.sendMail, data: ' + JSON.stringify(data));

    const recipientEmail = data['recipientEmail'];
    console.log('recipientEmail: ' + recipientEmail);

    const mailOptions = {
        from: 'Abc Support <[email protected]>',
        to: recipientEmail,
        html:
           `<p style="font-size: 16px;">Thanks for signing up</p>
            <p style="font-size: 12px;">Stay tuned for more updates soon</p>
            <p style="font-size: 12px;">Best Regards,</p>
            <p style="font-size: 12px;">-Support Team</p>
          ` // email content in HTML
    };

    mailOptions.subject = 'Welcome to Abc';

    return mailTransport.sendMail(mailOptions).then(() => {
        console.log('email sent to:', recipientEmail);
        return new Promise(((resolve, reject) => {
       
            return resolve({
                result: 'email sent to: ' + recipientEmail
            });
        }));
    });
});

Thanks also to: Micha's post

like image 26
Gene Bo Avatar answered Oct 21 '22 04:10

Gene Bo


You can send for free with Firebase extensions and Sendgrid:

https://medium.com/firebase-developers/firebase-extension-trigger-email-5802800bb9ea

like image 1
woshitom Avatar answered Oct 21 '22 02:10

woshitom