Last active
July 30, 2023 06:07
-
-
Save rajathithan/602a17e2eadb8c2a42e2b8224df095a0 to your computer and use it in GitHub Desktop.
Python script to send email from cloud function using customized html template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Python script to send email from cloud function using customized html template | |
# Author: Rajathithan Rajasekar | |
# Version : 1.0 | |
# Date: 07/30/2023 | |
import os | |
import pytz | |
import smtplib | |
from datetime import datetime | |
from email.mime.text import MIMEText | |
from email.mime.multipart import MIMEMultipart | |
# SMTP server hostname or ipaddress | |
SMTP_SERVER = "X.X.X.X" | |
# SMTP Port | |
SMTP_PORT = 25 | |
# Sender Email | |
FROM_EMAIL = "sender@someXXXXX.com" | |
# Receiver Email | |
TO_EMAIL = ["receiver1@someXXXX.com","receiver2@someXXXX.com"] | |
# Environment | |
env = "environment_name" | |
# Cloud Function Name | |
cfname = os.environ.get('K_SERVICE') | |
def prepare_html(event_data, context): | |
# Extract timestamp | |
ts = datetime.strptime(context.timestamp, '%Y-%m-%dT%H:%M:%S.%fZ') | |
# Creation of timezones | |
eastern = pytz.timezone('US/Eastern') | |
utc = pytz.timezone('UTC') | |
# Localize the UTC TimeZone | |
utc_ts = utc.localize(ts) | |
# Convert UTC to US Eastern TimeZone | |
eastern_ts = utc_ts.astimezone(eastern) | |
# Timestamp converted to Eastern timezone | |
timestamp = eastern_ts.strftime("%d %B, %Y - %I:%M %p") + " EST" | |
# Status of the Storage transfer Job | |
status=event_data['attributes']['eventType'] | |
# Create the HTML Template | |
html = """\ | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<style type="text/css"> | |
table, td {{ | |
border: 1px solid black; | |
border-collapse: collapse; | |
}} | |
td {{padding: 5px;}} | |
tr:hover {{background-color: coral; color: white;}} | |
tr:nth-child(even) {{background-color: #f2f2f2;}} | |
h2 {{ text-decoration: underline black }} | |
h2:hover {{color: #007FFF;}} | |
</style> | |
</head> | |
<body style="background-color: #fdf9f8; padding: 5px"> | |
<center> | |
<style> | |
@import url('https://fonts.googleapis.com/css/css?family=Roboto'); | |
</style> | |
<div style="background-color: #fff; width: 80%; border-radius: 7px; margin-top: 25px; font-family: roboto; padding: 10px"> | |
<p style="font-size: 15px;text-align: center;padding: 5px"> | |
<h2> | |
Notification from cloud function [{cfname}] | |
</h2> | |
<br> | |
</p> | |
<p style="font-size: 15px;text-align: left;padding: 5px"> | |
<i> | |
Hi Team,<br><br> | |
Below is the status of the {env} Storage Transfer Service Job.<br> | |
</i> | |
<table> | |
<tr><td>projectId</td><td>{projectId}</td></tr> | |
<tr><td>TransferJob</td><td>{transferjob}</td></tr> | |
<tr><td>Status</td><td>{status}</td></tr> | |
<tr><td>Event-Type</td><td>{type}</td></tr> | |
<tr><td>Topic-Name</td><td>{topic}</td></tr> | |
<tr><td>Timestamp</td><td>{timestamp}</td></tr> | |
</table> | |
</p> | |
<p style="font-size: 15px;text-align: left;padding: 5px"> | |
<i> | |
<br>Thanks. | |
</i> | |
</p> | |
</div> | |
</center> | |
</body> | |
</html> | |
""".format( | |
cfname=cfname, | |
env=env, | |
projectId=event_data['attributes']['projectId'], | |
transferjob=event_data['attributes']['transferOperationName'], | |
status=status, | |
type=event_data['@type'], | |
topic=context.resource['name'], | |
timestamp=timestamp, | |
) | |
# Determine if the Job is successful or not | |
if status != "TRANSFER_OPERATION_SUCCESS": | |
transfer = "Failure" | |
else: | |
transfer = "Success" | |
return MIMEText(html, "html"), transfer | |
def send_email(event_data, context): | |
#Message settings | |
message = MIMEMultipart("alternative") | |
message["From"] = FROM_EMAIL | |
message["To"] = ", ".join(TO_EMAIL) | |
# Prepare the html content | |
part, transfer = prepare_html(event_data, context) | |
# Update subject based on Job Status | |
if transfer == "Success": | |
message["Subject"] = env + " STS-Job Successful" | |
else: | |
message["Subject"] = env + " STS-Job Failed" | |
# Attach the html section to the message | |
message.attach(part) | |
# Create the SMTP context and send email | |
try: | |
with smtplib.SMTP(host=SMTP_SERVER, port=SMTP_PORT) as server: | |
server.set_debuglevel(2) | |
server.sendmail( | |
from_addr=FROM_EMAIL, | |
to_addrs=TO_EMAIL, | |
msg=message.as_string(), | |
) | |
except Exception as e: | |
print(f"An Exception Occurred - {e}") | |
return -1 | |
return "Email is sent successfully" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment