This recipe shows you how to send an email from a Cloud Function using SendGrid. Where applicable:
Replace [PROJECT-ID] with your Cloud Platform project ID
-
Follow the Cloud Functions quickstart guide to setup Cloud Functions for your project
-
Clone this repository
cd ~/ git clone https://github.com/jasonpolites/gcf-recipes.git cd gcf-recipes/sendgrid
-
Create an account on Sendgrid. You can either do this manually via the SendGrid website, or you can use the Google Cloud Launcher which will create an account for you and also integrate billing
-
Create SendGrid API key
- Log in to your SendGrid account at https://app.sendgrid.com
- Navigate to Settings => API Keys
- Create a new "General API Key"
- Ensure you select (at least) the "Mail Send" permission when you create the API key
- Copy the API Key when it is displayed (you will only see this once, make sure you paste it somewhere!)
-
Create a Cloud Storage Bucket to stage our deployment
gsutil mb gs://[PROJECT-ID]-gcf-recipes-bucket
-
Deploy the "sendEmail" function with an HTTP trigger
gcloud alpha functions deploy sendEmail --bucket [PROJECT-ID]-gcf-recipes-bucket --trigger-http
-
Call the "sendEmail" function:
gcloud alpha functions call sendEmail --data '{"sg_key": "[SENDGRID_KEY]", "to": "[RECIPIENT_ADDR]", "from": "[SENDER_ADDR]", "subject": "Hello from Sendgrid!", "body": "Hello World!"}'
- Replace SENDGRID_KEY with your SendGrid API KEY
- Replace RECIPIENT_ADDR with the recipient's email address
- Replace SENDER_ADDR with your SendGrid account's email address
-
Check the logs for the "sendEmail" function
gcloud alpha functions get-logs sendEmail
You should see something like this in your console
D ... User function triggered, starting execution
I ... Sending email to: [RECIPIENT_ADDR]
D ... Execution took 1 ms, user function completed successfully
This recipe comes with a suite of unit tests. To run the tests locally, just use npm test
npm install
npm test
The tests will also produce code coverage reports, written to the /coverage
directory. After running the tests, you can view coverage with
open coverage/lcov-report/index.html