remindme_caldav/email_alert.py

64 lines
2.2 KiB
Python
Raw Normal View History

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import ssl
import humanfriendly
def send_email(event, next_alert, next_event, config):
# Set up the SMTP server details
smtp_server = config["email"]["smtp_server"]
port = config["email"]["port"]
sender_email = config["email"]["username"]
receiver_email = config["email"]["recipient"]
password = config["email"]["password"]
# Event details
event_name = event["summary"]
event_description = event["description"]
event_location = event["location"]
event_date = next_event
event_delta = next_event - next_alert
total_seconds = event_delta.total_seconds()
human_readable_time = humanfriendly.format_timespan(total_seconds)
# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "Event Alert: '{}' @ {}".format(event_name, event_date)
# Add body to email
body = """\
Hi,
This is an event alert from remindme_caldav.
Event details:
---------------------------------
Event name: {}
Date/time: {}
Description: {}
Location: {}
Time until event: {}
---------------------------------
""".format(event_name, event_date, event_description, event_location, human_readable_time)
message.attach(MIMEText(body, "plain"))
text = message.as_string()
try:
# Create a secure SSL context and connect to the server
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server: # Use 'with' statement for automatic cleanup
server.ehlo() # Can be omitted
server.starttls(context=context) # Secure the connection
server.login(sender_email, password)
# Send email here
server.sendmail(sender_email, receiver_email, text)
print("Message sent via email")
return
except Exception as e:
# Print any error messages to stdout
print("An error occured when sending alert via email, please check your config. Message: {}".format(e))