Google Cloud Functions - with Sendgrid

I’ve been doing some simple sites for my friends, just to keep some muscle memory going. It’s hard being at 10000ft all the time. I really needed to get some code to production.

I remember how amazing it was to have people generate an email from my website, way back, in the long long ago. Well, the first time people get a website of their own, that seems to be an automatic desire.

What is the easiest way for someone to see that people are using their website? One request that comes up often is “a form that sends an email” to the site owner.

Well, sounds easy enough, but what is the right way? The first time I did this it was using C in a CGI-BIN. That idea still sends an uncomfortable tingle down my spine.

Today, I feel like this is a good fit for a “function” or Google Cloud Function to be more precise.

The landscape:

This keeps things relatively inexpensive and easy to collaborate on.

The Email Form

Well, it seems simple enough.

  • User fills in a form
  • User clicks button sending form data to the cloud function.
  • Cloud function calls Sendgrid - with form data as email body
  • User gets notified of success/failure
  • Website owner gets an email

I don’t use NodeJS every day, but I know it well enough to be comfortable starting this type of project.

At least that is what I thought a few hours ago.

I unsuccessfully tried to deploy my simple cloud function 3 times.

At this point, I choose to start over.

Google Cloud Function Hello World with NodeJS

Way easier than I expected:

  • Go to Cloud Functions
  • Create Function
  • Choose 256MB
  • Choose NodeJS 10 (beta)
  • Choose Inline Editor
    • The cool thing here is that it gives you a hello world example - I didn’t have to type anything
  • Click deploy

You now have a function deployed!

Moving on

Now I have proven to myself, that I can create a script and deploy it, back to business.

I figured out why it wasn’t deploying, I was missing an import.

I pushed out my function.

Now, I realize what is missing. I need to verify that this is a valid email address and that the owner of the email address sent it.

Next time a.k.a TODOs

  • Update the function, so that it sends a verification email to the address.
  • The verification function, verifies the user, then sends the email to the site owner.
  • If the user is not verified, no email will be sent to the site owner.

Significant bits

Because I plan on updating and making the repo public, I’ll just put these bits here for now:

const sgMail: require('@sendgrid/mail');

exports.sendgridEmail: async (req, res) => {
    try {
        if (req.method === 'POST') {
            let msg: {
                to: process.env.EMAIL_TO,
                subject: process.env.EMAIL_SUBJECT,
                text: process.env.EMAIL_TEXT,
                html: process.env.EMAIL_TExT
            await sgMail.send(msg);
    } catch (error) {
        if (error.response) {