What's the best way to send an e-mail via Python Google Cloud Function?
Jun 9
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 = 'SenderEmailAddress@gmail.com'
gmail_password = 'SenderEmailPassword'
sent_from = gmail_user
to = ['RecipientEmailAddress@gmail.com']
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='SenderEmailAddress@gmail.com',
to_emails='RecipientEmailAddress@gmail.com',
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)
1 answer
Accepted answer · original discussion
Jun 9
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
- activate a plan on GCP marketplace ( I use free plan, 12K mails/month)
- Create an api key in sendgrid
- 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.
- Create a service account with functions.invoker permission within your function
- Create new Cloud scheduler job
- Specify the frequency in cron format.
- Specify HTTP as the target type.
- Add the URL of your cloud function and method as always.
- Select the token OIDC from the Auth header dropdown
- Add the service account email in the Service account text box.
0 question comments
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.