2024-02-06 19:02:44 +00:00
|
|
|
import smtplib
|
|
|
|
from email.mime.multipart import MIMEMultipart
|
|
|
|
from email.mime.text import MIMEText
|
|
|
|
import ssl
|
2024-02-09 12:08:31 +00:00
|
|
|
import humanfriendly
|
2024-02-06 19:02:44 +00:00
|
|
|
|
2024-02-09 12:08:31 +00:00
|
|
|
def send_email(event, next_alert, next_event, config):
|
2024-02-06 19:02:44 +00:00
|
|
|
# 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
|
2024-02-09 12:08:31 +00:00
|
|
|
event_name = event["summary"]
|
|
|
|
event_description = event["description"]
|
|
|
|
event_location = event["location"]
|
2024-02-06 19:02:44 +00:00
|
|
|
event_date = next_event
|
|
|
|
event_delta = next_event - next_alert
|
2024-02-09 12:08:31 +00:00
|
|
|
total_seconds = event_delta.total_seconds()
|
|
|
|
human_readable_time = humanfriendly.format_timespan(total_seconds)
|
2024-02-06 19:02:44 +00:00
|
|
|
|
|
|
|
# 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,
|
2024-02-09 12:08:31 +00:00
|
|
|
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)
|
2024-02-06 19:02:44 +00:00
|
|
|
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)
|
2024-02-09 12:08:31 +00:00
|
|
|
print("Message sent via email")
|
|
|
|
return
|
2024-02-06 19:02:44 +00:00
|
|
|
except Exception as e:
|
|
|
|
# Print any error messages to stdout
|
2024-02-09 12:08:31 +00:00
|
|
|
print("An error occured when sending alert via email, please check your config. Message: {}".format(e))
|