Send Email From Google Cloud Functions (Python)

May 29, 2019

I would recommend using SendGrid, which allow 12,000 emails / month.

Edit requirements.txt.

# https://pypi.org/project/sendgrid/
sendgrid==6.0.5

Cloud Functions using Python

def send_welcome_email(request):
    import logging
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import Mail, Email
    from python_http_client.exceptions import HTTPError

    log = logging.getLogger(__name__)

    SENDGRID_API_KEY = 'SG.xx-mm...'
    sg = SendGridAPIClient(SENDGRID_API_KEY)

    APP_NAME = "Lua Software Code"
    name = "Desmond"

    html_content = f"""
    <p>Hello {name},</p>
    <br>
    <p>Welcome to <a href="https://code.luasoftware.com/">{APP_NAME}</a></p>
    <br>
    <p>From,</p>
    <p>Desmond Lua</p>
    """

    message = Mail(
        to_emails="to@email.com",
        from_email=Email('desmond.lua@luasoftware.com', "Desmond Lua"),
        subject=f"Welcome to {APP_NAME}",
        html_content=html_content
        )
    message.add_bcc("bcc@email.com")

    try:
        response = sg.send(message)
        return f"email.status_code={response.status_code}"
    except HTTPError as e:
        return e.message

NOTE: I read some notes regarding the need to enable billing for Google Clouds or enable Blaze Plan for Firebase for outgoing network traffic, not sure if this still hold true.

NOTE: SendGrid Templates with Parameters (Dynamic Template Data).

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.