Sending an email with SendGrid from Workflows


For notification purposes, especially in an asynchronous way, email is a great solution. I wanted to add an email notification step in Google Cloud Workflows. Since GCP doesn’t have an email service, I looked at the various email services available in the cloud: SendGrid, Mailgun, Mailjet, and even ran a quick Twitter poll to see what folks in the wild are using. I experimented with SendGrid, and the sign up process was pretty straightforward, as I was able to get started quickly, by creating an API key, and sending my first email with cURL command. 


Now comes the part where I needed to call that API from my workflow definition. And that’s actually pretty straightforward as well. Let’s see that in action:


- retrieve_api_key:
    assign:
        - SENDGRID_API_KEY: "MY_API_KEY"
- send_email:
    call: http.post
    args:
        url: https://api.sendgrid.com/v3/mail/send
        headers:
            Content-Type: "application/json"
            Authorization: ${"Bearer " + SENDGRID_API_KEY}
        body:
            personalizations:
                - to:
                    - email: to@example.com
            from:
                email: from@example.com
            subject: Sending an email from Workflows
            content:
                - type: text/plain
                  value: Here's the body of my email
    result: email_result
- return_result:
    return: ${email_result.body}


In the retrieve_api_key step, I simply hard-coded the SendGrid API key. However, you can of course store that secret in Secret Manager, and then fetch the secret key thanks to the Workflows Secret Manager connector (that’s probably worth a dedicated article!)


Then, in the send_email step, I prepare my HTTP POST request to the SendGrid API endpoint. I specify the content type, and of course, the authorization using the SendGrid API key. Next, I prepare the body of that request, describing my email, with a from field with a registered email user that I defined in SendGrid, a to field corresponding to the recipient, an email subject and body (just plain text, here). And that’s pretty much it! I just translated the JSON body sent in the cURL example from SendGrid’s documentation, into YAML (using a handy JSON to YAML conversion utility)


 

 
© 2012 Guillaume Laforge | The views and opinions expressed here are mine and don't reflect the ones from my employer.