Sending email on a specific day with Python.

Sending email on a specific day with Python.

The task was to send emails with random quotes from the data file on a specific day of the week. So, here we go... First, I need to know what day of the week that is. That's why I will need datetime module.

import datetime as dt

first I create now datetime object and now I have access to year, day, month and ets. in this moment:

now = dt.datetime.now()
day_of_week = now.weekday()
#print(day_of_week)    /sorry, my debugging trail :)

Then I read the data file and convert it to a list. After that I randomly choose the quote from a list and put it to the variable: with open("quotes.txt", "r") as data: data_list = data.readlines() quote = random.choice(data_list) The next step is to send this quote to email of my choice. And for that I created the variables at the head of the document for sender email and password:

my_email = "sender_email@mail.com"
password = "sender_password"

Now I create the function that will send the emails with randomly chosen quotes and I use :

def send_email():
    with smtplib.SMTP("outlook.office365.com") as connection:
        connection.starttls()
        connection.login(user=my_email, password=password)
        connection.sendmail(from_addr=my_email, to_addrs="receiver_address@yahoo.com", msg=f"Subject: Motivational quote\n\n{quote}")

Finally, as I want to send the email on a specific day I create the if statement and check if todays day corresponds a day of sending. For that I created the constant DAY_OF_SENDING which is gonna be equal to the number of the day, since as a default the weekdays in daytime module are going as numbers.

if day_of_week == DAY_OF_SENDING:
    send_email()