Tuesday, November 1, 2022

Python - smtplib and datetime modules (Day 32)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Setting up a Google Account



In order to use Gmail SMTP Server,  we need to change some settings of Google Accounts

We can enable "less secure apps" feature in Google and our python code can use this account's credential to send out emails.

Unfortunately, it is no longer available.


The alternative way is to use an App Password.


An App Password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account. App Passwords can only be used with accounts that have 2-Step Verification turned on.

After enabling 2-Step Verification, we can see 'App passwords' option under Signing in to Google section.


Then we can create app passwords to be used by our python code instead of google account password.



smtplib module





Ex:
import smtplib

GMAIL_SMTP_SERVER_ADDRESS = "smtp.gmail.com"
GMAIL_SMTP_TLS_PORT = 587
MY_EMAIL_ADDRESS = "your_account@gmail.com"

# Create a connection to SMTP Provider
connection = smtplib.SMTP(
host=GMAIL_SMTP_SERVER_ADDRESS,
port=GMAIL_SMTP_TLS_PORT
)

# Make this connection secure
connection.starttls()

# Login with your Google App Password
connection.login(user=MY_EMAIL_ADDRESS, password="your_app_password")

# Send an email
connection.sendmail(
    from_addr=MY_EMAIL_ADDRESS,
    to_addrs="your_receiver@gmail.com",
    msg="Subject: Python smtplib exp\n\nHello World!\n",
)

# Close connection
connection.close()


Result:



Good Article to read:



datetime module





Ex:
import datetime as dt

# Return the current local date and time.
now = dt.datetime.now()

# <class 'datetime.datetime'>
print(type(now))

# 2022-11-01 02:55:54.186915
print(now)

# 2022
print(now.year)

# 11
print(now.month)

# 1
print(now.day)

# Return day of the week, where Monday == 0 ... Sunday == 6.
# 1
print(now.weekday())


# Create a custom datetime
my_birthday = dt.datetime(year=1999, month=12, day=1)

# 1998-12-01 00:00:00
print(my_birthday)


Challenge - Send Motivational Quotes on Mondays via Email



#1 Use datetime module to determine if the current day is Monday
#2 Open 'quotes.txt' file to get the all quotes
#3 Use random module to pick one quote randomly
#4 Use smtplib to send out Monday Motivation


quotes.txt
"When you arise in the morning think of what a privilege it is to be alive,
to think, to enjoy, to love..." - Marcus Aurelius "Either you run the day or the day runs you." - Jim Rohn

Ex:
import random
import datetime as dt
import smtplib

GMAIL_SMTP_SERVER_ADDRESS = "smtp.gmail.com"
GMAIL_SMTP_TLS_PORT = 587
MY_EMAIL_ADDRESS = "your_account@gmail.com"


def get_quote():
    """Open quotes.txt and randomly pick one quote"""

    # Open file
    with open("quotes.txt") as file:
        # Use random module to pick one quote
        quote = random.choice(file.readlines())

    return quote


def is_monday():
    """Check if the current day is Monday"""

    now = dt.datetime.now()
    return now.weekday() == 0


def send_email(message):
    """Send an email with message"""

    # Create a connection to SMTP Provider
    with smtplib.SMTP(
        host=GMAIL_SMTP_SERVER_ADDRESS, port=GMAIL_SMTP_TLS_PORT
    ) as connection:

        # Make this connection secure
        connection.starttls()

        # Login with your Google App Password
        connection.login(
user=MY_EMAIL_ADDRESS,
password="your_app_password"
)

        # Send an email
        connection.sendmail(
            from_addr=MY_EMAIL_ADDRESS,
to_addrs="your_receiver@gmail.com",
msg=message
        )


# if it is Monday, then we will send a quote to motivate ourselves
if is_monday():
    quote = get_quote()

    send_email(f"Subject: Monday Motivation\n\n{ quote }\n")


Project - Automated Birthday Wisher



#1 Fill out bithdays.csv with 'name,email,year,month,day' format
#2 Use pandas module to read csv
#3 Use list comprehension for filtering to get the birthdays which match today
#4 Open file and use random module to get the letter template
#5 Use smtplib module to send out birthday emails

letter_templates/letter_1.txt: (1~3)
Dear [NAME], Happy birthday! All the best for the year! Frank

birthdays.csv
name,email,year,month,day Mom,mom@your_email_provider,2022,11,01 Dad,dad@your_email_provider,2022,11,02

Ex:
import datetime as dt
import pandas
import random
import smtplib

GMAIL_SMTP_SERVER_ADDRESS = "smtp.gmail.com"
GMAIL_SMTP_TLS_PORT = 587
MY_EMAIL_ADDRESS = "your_account@gmail.com"

now = dt.datetime.now()
birthdays_data_frame = pandas.read_csv("birthdays.csv")


def send_email(email_address, message):
    """Send an email with message"""

    # Create a connection to SMTP Provider
    with smtplib.SMTP(
        host=GMAIL_SMTP_SERVER_ADDRESS, port=GMAIL_SMTP_TLS_PORT
    ) as connection:

        # Make this connection secure
        connection.starttls()

        # Login with your Google App Password
        connection.login(user=MY_EMAIL_ADDRESS,
password="your_app_password")

        # Send an email
        connection.sendmail(
            from_addr=MY_EMAIL_ADDRESS,
to_addrs=email_address,
msg=message
        )


def get_content_from_an_random_letter():
    """Get random letter content"""

    # Pick a random letter
    random_letter_path =
f"letter_templates/letter_{random.randint(1,3)}.txt"

    # Open letter template file and return its content
    with open(random_letter_path) as file:
        return file.read()


# List Comprehension
# Get the birthdays if its date match today
match_birthdays = [
    row
    for (_index, row) in birthdays_data_frame.iterrows()
    if row["month"] == now.month and row["day"] == now.day
]

# Loop through birthdays and send emails
for person in match_birthdays:

    # Generate birthday message randomly by template
    message = get_content_from_an_random_letter().replace("[NAME]",
person["name"])

    # Send an email
    send_email(person["email"],
f"Subject: Happy Birthday\n\n{ message }\n")


No comments:

Post a Comment