Using Secret Manager and Cloud Functions to send mail with SendGrid

Jeffrey S. Levine
Google Cloud - Community
2 min readJan 6, 2022

--

One of the things I like the most about working for Google Cloud is the chance to share things I’ve learned and generalize them for others. In a previous article I wrote about a project I did to send emails from Cloud Pub/Sub using a Google Cloud Function. In that particular case, there were requirements to use only native SMTP capabilities and all messages had to be sourced from a static IP.

I had the opportunity to revisit this without these requirements and do this a different way. I still use Cloud Functions but call SendGrid to do the work. SendGrid is one of the email services available on the Google Cloud Marketplace.

After signing up for SendGrid, I had to generate an API key. API keys, like any kind of credential, need to be protected. I decided to use Secret Manager for this. You use Secret Manager to store secrets (like passwords, keys, and so forth). Secret Manager encrypts the information and supports versioning and resource permissions. You just create a service account and add the Secret Accessor permission in the Secret Manager console and then attach the service account to the Cloud Function.

I developed two Cloud Functions, one to handle messages coming in from Cloud Pub/Sub, the other from HTTP calls. The Cloud Function parses the message, gets API key from Secret Manager and then calls SendGrid. Here are diagrams of the two uses cases.

Cloud Function that uses Secret Manager to Call SendGrid from Cloud Pub/Sub

If you’d like to learn more about this, take a look at the GitHub repo. Also, please note that although I work for Google Cloud, I am writing on my own and not in any official capacity.

Happy coding!

--

--

Jeffrey S. Levine
Google Cloud - Community

I am a Customer Engineer for Google. I help organizations evaluate and adopt Google Cloud. These articles reflect my views and not those of my employer.