Implementing Emailing with Firebase Cloud Features

For our web application, we currently use the Firebase free plan and must send emails to various events / triggers. The problem is that I thought Mailgun would do just fine with its cloud-based features, but it looks like you can only use their APIs with the Firebase board, which we are not going to use right now when our application is still in In development, thus, we were kind of stuck without knowing how to implement email functionality with Firebase with a minimum amount of money (we can always pay or pay more when we have a little understanding if our application really brings any ribyl) ... Can someone help me.With any way to do this in (almost) free form at the moment - which we can update at any time later?

Thank! Sonya Piyush

+4
source share
2 answers

If you go to the Blaze plan, you will pay only for what you use, and for the functions of the cloud, you will still receive the number of free executions.

I do not know the specifics of your application, but while in development for most applications you are unlikely to take more than a few dollars a month in fees (and, perhaps, only a penny).

+2
source

firebase . (http-) , , ( ) - . :

:

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const rp = require('request-promise');

//google account credentials used to send email
const mailTransport = nodemailer.createTransport(
    `smtps://user@domain.com:password@smtp.gmail.com`);

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

  //recaptcha validation
  rp({
        uri: 'https://recaptcha.google.com/recaptcha/api/siteverify',
        method: 'POST',
        formData: {
            secret: 'your_secret_key',
            response: req.body['g-recaptcha-response']
        },
        json: true
    }).then(result => {
        if (result.success) {
            sendEmail('recipient@gmail.com', req.body).then(()=> { 
              res.status(200).send(true);
            });
        }
        else {
            res.status(500).send("Recaptcha failed.")
        }
    }).catch(reason => {
        res.status(500).send("Recaptcha req failed.")
    })

});

// Send email function
function sendEmail(email, body) {
  const mailOptions = {
    from: `<noreply@domain.com>`,
    to: email
  };
  // hmtl message constructions
  mailOptions.subject = 'contact form message';
  mailOptions.html = `<p><b>Name: </b>${body.rsName}</p>
                      <p><b>Email: </b>${body.rsEmail}</p>
                      <p><b>Subject: </b>${body.rsSubject}</p>
                      <p><b>Message: </b>${body.rsMessage}</p>`;
  return mailTransport.sendMail(mailOptions);
}

, :

<form class="rsForm" action="/sendEmailCF" method="post">
    <div class="input-field">
        <label>Name</label>
        <input type="text" name="rsName" value="">
        <span class="line"></span>
    </div>

    <div class="input-field">
        <label>Email</label>
        <input type="email" name="rsEmail" value="">
        <span class="line"></span>
    </div>

    <div class="input-field">
        <label>Subject</label>
        <input type="text" name="rsSubject" value="">
        <span class="line"></span>
    </div>

    <div class="input-field">
        <label>Message</label>
        <textarea rows="4" name="rsMessage"></textarea>
        <span class="line"></span>
    </div>

    <input type="hidden" name="rsLang" value="en" />

    <span class="btn-outer btn-primary-outer ripple">
        <input class="formSubmitBtn btn btn-lg btn-primary" type="submit" data-recaptcha="global" value="Send">
    </span>
    <div id="recaptcha-global"></div>
</form>

Script submit:

$('.formSubmitBtn').on('click', function (e) {
    glForm = $(this).closest('.rsForm');
    var recaptchaId = 'recaptcha-' + $(this).data('recaptcha');
    var rsFormErrors = false;
    glFormAction = glForm.attr('action');
    var rsFormFields = glForm.find('.input-field');
    var rsFormName = glForm.find("[name='rsName']");
    var rsFormEmail = glForm.find("[name='rsEmail']");
    var rsFormMessage = glForm.find("[name='rsMessage']");

    // Button ripple effect
    ripple($(this).parent(), e.pageX, e.pageY);

    // Reset form errors
    rsFormFields.removeClass('error');
    rsFormErrors = false;

    // Validate form fields
    if(!rsFormName.val()) {
        rsFormErrors = true;
        rsFormName.parent().addClass('error');
    }

    if(!rsFormEmail.val() || !isValidEmail(rsFormEmail.val())) {
        rsFormErrors = true;
        rsFormEmail.parent().addClass('error');
    }

    if(!rsFormMessage.val()) {
        rsFormErrors = true;
        rsFormMessage.parent().addClass('error');
    }

    if(rsFormErrors) {
        // if has errors - do nothing
        return false;
    } else {

        if(rca[recaptchaId] === undefined){
            rca[recaptchaId] = grecaptcha.render(recaptchaId, {
                'sitekey' : 'sitekey',
                'callback' : onExecutedCaptcha,
                'size' : 'invisible',
                'badge':'inline'
            });

        } else {
            grecaptcha.reset(rca[recaptchaId]);
        }

        grecaptcha.execute(rca[recaptchaId]);
        return false;
    }
});

Script recaptcha :

function onExecutedCaptcha(token) {

  var sendingMsg = null, textMsg = null, textErr = null;
  var lang = glForm.find("[name='rsLang']").val();

  if(lang == 'es') {
      sendingMsg = 'Enviando mensaje...';
      textMsg = 'Tu mensaje se ha enviado con \u00e9xito!';
      textErr = 'Algo ha salido mal. Intenta mas tarde';
  } else {
      textMsg = 'Your email was sent successfully!';
      textErr = 'Oops! Something went wrong. Please try again.';
      sendingMsg = 'Sending email...';
  }

  swal({
    text: sendingMsg,
    button: false,
    closeOnClickOutside: false,
    closeOnEsc: false,
  });

    $.post( glFormAction,
        glForm.serialize(),
        function (response) {
            grecaptcha.reset();
            var data = jQuery.parseJSON( response );
            swal.close();

            if(data){
                swal({
                  text: textMsg,
                  icon: "success",
                });
                 glForm.find("input[type=text], input[type=email], textarea").val("");
            } else {
                swal({
                  text: textErr,
                  icon: "error",
                });
            }
        }
    );
}
+1

Source: https://habr.com/ru/post/1680446/


All Articles