Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to send an e-mail via Python Google Cloud Function?

I'm trying to write a Python Google Cloud Function to send an automated e-mail to the same G-mail address at the same time every day (e.g. every day at 00:00). What's the easiest way to accomplish this? I couldn't find any online tutorials or guidance in the online documentation...Thanks in advance!

Here's what I've tried so far but neither approach seems to work (real e-mail addresses, passwords and API keys hidden for obvious reasons)

Approach 1: Using smtplib (function body)

import smtplib

gmail_user = '[email protected]'
gmail_password = 'SenderEmailPassword'

sent_from = gmail_user
to = ['[email protected]']
subject = 'Test e-mail from Python'
body = 'Test e-mail body'

email_text = """\
From: %s
To: %s
Subject: %s

%s
""" % (sent_from, ", ".join(to), subject, body)

server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print('Email sent!')

Approach 2: Using SendGrid API (function body)

import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email='[email protected]',
    to_emails='[email protected]',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')

try:
    sg = SendGridAPIClient("[SENDGRID API KEY]")
    #sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.message)
like image 285
abgo2020 Avatar asked Jun 09 '20 12:06

abgo2020


People also ask

How do I send an email from Google cloud?

In the Google Cloud console, go to the Create a firewall rule page. Choose a name for the firewall rule. Under Network, select the network that is hosting the VM instance that you intend to send email messages from. Under Direction of traffic, select Egress.

How do I use Python to send an email?

Set up a secure connection using SMTP_SSL() and . starttls() Use Python's built-in smtplib library to send basic emails. Send emails with HTML content and attachments using the email package.

Can I send email with Python Gmail?

Note: When sending emails with Python, you must ensure your SMTP connection is encrypted, so your message and login credentials are not easily accessed by others. SSL (Secure Sockets Layer) and TLS (Transport Layer Security) are two protocols that can be used to encrypt an SMTP connection.

Can Pubsub send emails?

Overview. pubsub_sendmail is a Google Cloud Function that can be triggered by a Google Cloud Pub/Sub which then sends an email using Python smtplib to the desired recipient. You can also have the email come from a static IP address by using a VPC Access Connector along with Cloud NAT.


1 Answers

The best way to send emails using a Cloud function is by using an Email third party service.

GCP offers discounts for Sendgrid and Mailjet these services must be enabled via GCP marketplace to apply for this offers.

The configuration with sendgrid is very easy

  1. activate a plan on GCP marketplace ( I use free plan, 12K mails/month)
  2. Create an api key in sendgrid
  3. validate your sendgrid account email (use the email that you received)

In cloud functions side you need to create a variable environment with your fresh sendgrid api key.

EMAIL_API_KEY = your awesome api key

and you can deploy the following example code

requirements.txt:

sendgrid

*without specify version to install latest available

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

    sg = SendGridAPIClient(os.environ['EMAIL_API_KEY'])

    html_content = "<p>Hello World!</p>"

    message = Mail(
        to_emails="[Destination]@email.com",
        from_email=Email('[YOUR]@gmail.com', "Your name"),
        subject="Hello world",
        html_content=html_content
        )
    message.add_bcc("[YOUR]@gmail.com")

    try:
        response = sg.send(message)
        return f"email.status_code={response.status_code}"
        #expected 202 Accepted

    except HTTPError as e:
        return e.message

To schedule your emails, you could use Cloud Scheduler.

  1. Create a service account with functions.invoker permission within your function
  2. Create new Cloud scheduler job
  3. Specify the frequency in cron format.
  4. Specify HTTP as the target type.
  5. Add the URL of your cloud function and method as always.
  6. Select the token OIDC from the Auth header dropdown
  7. Add the service account email in the Service account text box.
like image 79
Jan Hernandez Avatar answered Sep 27 '22 18:09

Jan Hernandez