TIL Python Basics Day 32 - SMTP, datetime / Birthday Wisher

이다연·2021년 1월 16일
0

Udemy Python Course

목록 보기
31/64
post-thumbnail

Send Email (smtplib) & datetime

SMTP

SMTP (Simple Mail Transfer Protocol) is a post man delivering through email servers
-a way for us to connect to our email providers' smtp email server
-.starttls() : tls(Transport Layer Security) encrypted

import smtplib

my_email = "testpythondy@gmail.com" #modify the security setting
my_password = d
yahoo_email = "testpythondy@yahoo.com"

#smtp.mail.yahoo.com

with smtplib.SMTP("smtp.gmail.com") as connection:
    connection.starttls()
    connection.login(user=my_email, password=my_password)
    connection.sendmail(
        from_addr=my_email,
        to_addrs=yahoo_email,
        msg="Subject: Hello again\n\n This is the body of my email." )

datetime module

preloaded with python, no need to install
can get current date and time

  • datetime module has datetime class
  1. datetime module and class have the same name (can be confusing)
#1
import datetime 

datetime.datetime.now()
  module.class
  1. when importing module, renamed it to avoid repeating the same name as class
#2
import datetime as dt 

dt.datetime.now()
  1. you are only importing the datetime class within tha datetime file.
#3
from datetime import datetime 

datetime.now()

e.g.2

import datetime as dt



now = dt.datetime.now() #module.class.now()
year = now.year

day_of_week = now.weekday()
print(day_of_week) #4 -> friday

date_of_birth = dt.datetime(year=1991, month=8, day=2)
print(date_of_birth)
#printed: 1991-08-02 00:00:00

Task.1 Sending motivational quote email every Friday.

utf8 Encoding/Decoding problem


import datetime as dt
import random
import smtplib

now = dt.datetime.now()
day_of_week = now.weekday()
print(day_of_week)
if day_of_week == 4:
    with open("quotes.txt", 'rt', encoding='UTF8') as q:
        content = q.readlines()
    print(content)
    quote = random.choice(content)
    print(quote)

    #-----------------------------email---------------------------------------

    my_email = "testpythondy@gmail.com"
    my_password = d
    yahoo_email = "testpythondy@yahoo.com"

    #smtp.mail.yahoo.com
    #smtp: a way for us to connect to our email providers' smtp email server
    with smtplib.SMTP("smtp.gmail.com") as connection:
        connection.starttls()
        connection.login(user=my_email, password=my_password)
        connection.sendmail(
            from_addr=my_email,
            to_addrs=yahoo_email,
            msg=f"Subject: Today's motivational quote.\n\n {quote}".encode('utf-8')) #this fixed ascii problem

Project: Birthday Wisher

##################### Normal Starting Project ######################

import pandas
import datetime as dt
import random
import smtplib

PLACEHOLDER = "[NAME]"
sentby = "Angela"

now = dt.datetime.now()
now_month = now.month
now_day = now.day
today = (now_month, now_day)
print(today)

#fetch the data
df = pandas.read_csv("birthdays.csv")
birthday_df = df.to_dict(orient='records')
print(birthday_df)

for person in birthday_df:
    if today == (person['month'], person['day']):
        name = person['name']
print(name)
#random pick letter format

letter = ["letter_1.txt", "letter_2.txt", "letter_3.txt"]
picked_letter = random.choice(letter)
print(picked_letter)

#replace name on the txt.file
#can use comprehension
with open(f"letter_templates/{picked_letter}", "r") as letter:
    letter_template = letter.read()
    new_letter = letter_template.replace(PLACEHOLDER, name)

# you don't need this bits 
# with open(f"letter_templates/Birthday_wish_to_{name}.txt", mode="w") as f_letter:
#     f_letter.write(new_letter)
#
# with open(f"letter_templates/Birthday_wish_to_{name}.txt", mode="r") as f:
#     content = f.read()

#send letter
my_email = "testpythondy@gmail.com"
my_password = deleted
yahoo_email = "testpythondy@yahoo.com"

with smtplib.SMTP("smtp.gmail.com") as connection:
    connection.starttls()
    connection.login(user=my_email, password=my_password)
    connection.sendmail(
        from_addr=my_email,
        to_addrs=yahoo_email,
        msg=f"Subject: Happy Birthday\n\n {new_letter}".encode('utf-8'))





HINT 3: Use dictionary comprehension to create a dictionary from birthday.csv that is formated like this:
birthdays_dict = {
     (birthday_month, birthday_day): data_row
 }
#Dictionary comprehension template for pandas DataFrame looks like this:
 new_dict = {new_key: new_value for (index, data_row) in data.iterrows()}
#e.g. if the birthdays.csv looked like this:
 name,email,year,month,day
 Angela,angela@email.com,1995,12,24
#Then the birthdays_dict should look like this:# birthdays_dict = {
     (12, 24): Angela,angela@email.com,1995,12,24
 }

#HINT 4: Then you could compare and see if today's month/day tuple matches one of the keys in birthday_dict like this:
 if (today_month, today_day) in birthdays_dict:

to compare the data format when using .readlines() vs to_dict()

with open("birthdays.csv") as bday:
    b = bday.readlines()
print(b)
#printed format: list \n
['name,email,year,month,day\n', 'Test,test@email.com,1961,12,21\n', 'Jack, testpythondy@yahoo.com,1991,01,15\n', ...]


df = pandas.read_csv("birthdays.csv")
birthday_df = df.to_dict(orient='records')
print(birthday_df)
#printed format: each dict inside list
[{'name': 'Test', 'email': 'test@email.com', 'year': 1961, 'month': 12, 'day': 21}, {'name': 'Jack', 'email': ' testpythondy@yahoo.com', 'year': 1991, 'month': ...]

Run my code in the cloud

I can set the time for this task to run automatically.
python anywhere

🎉Yay halfway done!🎺

I am halfway through the 100 days of code!

Note.
Design Pattern (Solution)

profile
Dayeon Lee | Django & Python Web Developer

0개의 댓글