Raspberry_Pi_Project/import_smtplib.py

57 lines
1.8 KiB
Python
Raw Normal View History

2025-01-09 21:42:06 +01:00
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import datetime
# email credentials and recipient information
email_user = "e-mail of sender"
email_password = "password for the e-mail account of the sender"
email_send = "e-mail of receiver"
# schedule of the emails
email_schedule = {
"2025-01-06": "Hallo, morgen ist der Tag für Papier.",
"2025-01-07": "Hallo, morgen ist der Tag für Karton.",
"2025-01-08": "Hallo, morgen ist der Tag für Metal.",
}
# today's date in the format YYYY-MM-DD
today = datetime.now().strftime("%Y-%m-%d")
# is there an email for today?
if today in email_schedule:
# subject of the email
subject = f"Email for {today}"
# get email body for today
body = email_schedule[today]
# creating email message
msg = MIMEMultipart()
msg["From"] = email_user
msg["To"] = email_send
msg["Subject"] = subject
# attaching the body of the email as plain text
msg.attach(MIMEText(body, "plain"))
# converting the message to a string
text = msg.as_string()
# initializing the server variable
server = None
# sending the email
try:
# connecting to gmail's smtp server
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
# logging in to the account
server.login(email_user, email_password)
# sending the mail
server.sendmail(email_user, email_send, text)
print(f"Email for {today} sent successfully.")
except Exception as e:
print(f"Failed to send email: {e}")
finally:
# checking the status of the server
if server:
# closing the email server connection
server.quit()
else:
print(f"No email scheduled for {today}.")