Send Email from Google Cloud Function

The easiest method to send emails from Google Cloud Function is the using of service. It allows you to send 100 emails in a day on the free account. And it’s very easy to integrate with. Below is an example of how you can use it with example of the code.

The volume which offers for free is quite enough to use for some rare notifications. You just need to create an API key to start using it. After creation of an account on SendGrid, go to settings and create API Key. This is all you need to start sending emails.

main.py

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

    log = logging.getLogger(__name__)

    SENDGRID_API_KEY = 'SG.HrJR_Npd...'
    sg = SendGridAPIClient(SENDGRID_API_KEY)
	
    json = request.get_json()
    id = json['ID']
    
    html_content = f"""
    

ID: {id}

""" message = Mail( to_emails="recipient@email.com", from_email=Email('notifications@email.com', "Notifications User"), subject=f"Email Topic", html_content=html_content ) try: response = sg.send(message) return f"email.status_code={response.status_code}" except HTTPError as e: return e.message

requirements.txt

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

Now if you send a proper JSON to the HTTP endpoint of the cloud function, it will send an email.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Post

%d bloggers like this: