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)
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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With