Spaces:
Sleeping
Sleeping
File size: 2,345 Bytes
9439b9b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
import os
import smtplib
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate, make_msgid
import pytz
from markdown import markdown
def get_timezone_by_ip(ip, session):
try:
data = session.get(f'https://worldtimeapi.org/api/ip/{ip}').json()
return data['timezone']
except Exception:
return 'UTC'
def ts_to_str(timestamp, timezone):
# Create a timezone-aware datetime object from the UNIX timestamp
dt = datetime.fromtimestamp(timestamp, pytz.utc)
# Convert the timezone-aware datetime object to the target timezone
target_timezone = pytz.timezone(timezone)
localized_dt = dt.astimezone(target_timezone)
# Format the datetime object to the specified string format
return localized_dt.strftime('%Y-%m-%d %H:%M:%S (%Z%z)')
def send_email(job_info):
if job_info.get('email'):
try:
email_info = job_info.copy()
email_serv = os.getenv('EMAIL_SERV')
email_port = os.getenv('EMAIL_PORT')
email_addr = os.getenv('EMAIL_ADDR')
email_pass = os.getenv('EMAIL_PASS')
email_form = os.getenv('EMAIL_FORM')
email_subj = os.getenv('EMAIL_SUBJ')
for key, value in email_info.items():
if key.endswith("time") and value:
email_info[key] = ts_to_str(value, get_timezone_by_ip(email_info['ip']))
server = smtplib.SMTP(email_serv, int(email_port))
# server.starttls()
server.login(email_addr, email_pass)
msg = MIMEMultipart("alternative")
msg["From"] = email_addr
msg["To"] = email_info['email']
msg["Subject"] = email_subj.format(**email_info)
msg["Date"] = formatdate(localtime=True)
msg["Message-ID"] = make_msgid()
msg.attach(MIMEText(markdown(email_form.format(**email_info)), 'html'))
msg.attach(MIMEText(email_form.format(**email_info), 'plain'))
server.sendmail(email_addr, email_info['email'], msg.as_string())
server.quit()
gr.Info('Email notification sent.')
except Exception as e:
gr.Warning('Failed to send email notification due to error: ' + str(e))
|