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 w
Solution 1:
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
defemail(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)
returnf"email.status_code={response.status_code}"#expected 202 Acceptedexcept 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.
Post a Comment for "What's The Best Way To Send An E-mail Via Python Google Cloud Function?"