◎ Python/Udemy Python

Day 032 - SMTP와 Datetime 활용

reo91004 2024. 3. 8. 13:52
반응형

시작하며

파이썬에서는 smtplib 모듈을 사용해 이메일을 보낼 수 있습니다. 내장 라이브러리로, 따로 설치할 필요는 없습니다.

시작하기 전에, Google의 정책 변경으로 단순히 아이디와 비밀번호만 기입해서는 파이썬에서 이메일을 보낼 수 없습니다. 이에 대해서 이 분 블로그가 스크린샷으로 설명을 되게 잘해주셔서 링크해봅니다.

smtplib

import smtplib

my_email = "your_email"
password = "your_password"

connection = smtplib.SMTP("smtp.gmail.com")
connection.starttls()
connection.login(user=my_email, password=password)
connection.sendmail(from_addr=my_email, to_addrs="your_email", msg="Hello")
connection.close()
  • my_emailpasaword에는 본인의 이메일, 앱 비밀번호를 넣으면 됩니다.
  • connection.starttls()는 이메일 서버와의 연결을 안전하게 만드는 암호화 처리를 합니다.

 

위 코드를 실행하면 아래 사진처럼 메일이 전송되지만, 제목을 설정하지 않았기 때문에 대부분 스팸메일함에 도착해 있습니다.

 

 

 

이를 스팸처럼 보이지 않게 하려면 제목 줄을 추가하면 됩니다. `sendmail` 부분을 변경해봅시다.

import smtplib

my_email = "your_email"
password = "your_password"

connection = smtplib.SMTP("smtp.gmail.com")
connection.starttls() # 이메일 서버와의 연결을 안전하게 만듦 (암호화)
connection.login(user=my_email, password=password)
connection.sendmail(
    from_addr=my_email,
    to_addrs="your_email", 
    msg="Subject:Hello!\n\nTest")
connection.close()

 

msg에 한글을 넣으면 인코딩 때문에 오류가 납니다. 추후 MIMEText 모듈을 사용해 해결이 가능합니다.

 

아직도 스팸메일함에서 볼 수 있긴 하지만, 제대로 제목과 본문이 구분 된 모습을 볼 수 있습니다.

 

 

 

여기서 connection.close()을 삭제하고 싶다면 with as 구문을 사용할 수도 있습니다.

 

import smtplib

my_email = "your_email"
password = "your_password"

with smtplib.SMTP("smtp.gmail.com") as connection:
    connection = smtplib.SMTP("smtp.gmail.com")
    connection.starttls() # 이메일 서버와의 연결을 안전하게 만듦 (암호화)
    connection.login(user=my_email, password=password)
    connection.sendmail(
        from_addr=my_email,
        to_addrs="your_email",
        msg="Subject:Hello!\n\nTest")

 

datetime

datetime 모듈은 날짜와 시간을 다룰 수 있게 해주는 유용한 모듈입니다. datetime 모듈도 파이썬에 내장되어 있기 때문에 간단하게 import만 해주시면 됩니다.

예시로 몇 가지 코드를 사용해봅시다.

import datetime as dt

now = dt.datetime.now()

# datetime에서도 특정 요소를 얻을 수 있음.
year = now.year # 년 추출
month = now.month # 월 추출 
day_of_week = now.weekday() # 월화수목금토일 출력 (0부터 시작)
print(day_of_week)

# now가 아니더라도 특정 날짜를 직접 만들 수 있음.
date_of_brith = dt.datetime(year=2000, month=6, day=28, hour=23)
print(date_of_brith)

 

초미니 프로젝트

미니 프로젝트를 하나 만들어 봅시다! quotes 메모장에 있는 동기부여 글귀들을 긁어와, 월요일마다 메일로 보내는 프로젝트입니다. 구현해야 할 기능들을 차근차근 적어봅시다.

  1. 월요일마다 보내야 합니다.
  2. 글귀를 긁어와 데이터형으로 저장해야 합니다.
  3. 이메일을 보내야 합니다.

최근 Class를 너무 쓰지 않아서 일부러 써먹어보았고, 조금 더 세부적인? 완성도를 높이는 것을 목적으로 구현해 보았습니다.

import smtplib
import datetime as dt
from random import *

class Mail:
    def __init__(self, dict) -> None:
        self.my_email = "your_email"
        self.password = "your_passwowrd"
        self.dict = dict

    def select_quote(self):
        return choice(list(self.dict.items()))

    def send_mail(self):
        author, text = self.select_quote()
        # print(author, text)
        with smtplib.SMTP("smtp.gmail.com") as connection:
            connection = smtplib.SMTP("smtp.gmail.com")
            connection.starttls()
            connection.login(user=self.my_email, password=self.password)
            connection.sendmail(
                from_addr=self.my_email,
                to_addrs="your_email",
                msg=f"Subject:name - {author}!\n\n{text}"
            )

# 오늘의 글귀, 저자 dict으로 변환
dict = {}

with open("Day 032/quotes.txt", "r") as files:
    for file in files:
        text, person = file.rsplit(' - ', 1)
        text, person = text.strip(), person.strip()
        dict[person] = text

day_of_week = dt.datetime.now().weekday()

if day_of_week == 0: # 오늘이 월요일이라면, 이메일 전송
    send_quote = Mail(dict)
    send_quote.send_mail()

한번 코드를 뜯어봅시다.

제일 먼저 quotes.txt에서 글귀를 가져와 딕셔너리형으로 저장하는 부분을 구현했습니다.

   with open("Day 032/quotes.txt", "r") as files:
    for file in files:
        text, person = file.rsplit(' - ', 1)
        text, person = text.strip(), person.strip()
        dict[person] = text

 

우선 읽기 모드로 가져와 준 후, file로 한 줄씩 가져옵니다. 메모장에 글귀들이

 

"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

 

이런 식으로 저장되어 있으므로 text, person = file.rsplit(' - ', 1)을 활용합니다. 이 코드는 - 기준으로 문장과 저자를 구분하는데, 혹여나 문장 안에 -가 들어갈 것을 염려해 rsplit으로 오른쪽부터 최대 1번만 나누어진 결과를 도출하므로 결과적으로

text : "When you arise in the morning think of what a privilege it is to be alive, to think, to enjoy, to love..."
person : Marcus Aurelius

 

위처럼 삽입될 것입니다.

 

datetime에서 weekday 메서드를 사용할 시, 0부터 6까지 월화수목금토일을 표현한다 했으므로 0일 때, 즉 월요일일 때만 Mail 클래스를 호출하도록 합니다.

 

Mail 클래스를 보면, 생성자로 my_emailpassword, dict가 있습니다. 여기서 이메일과 비밀번호는 사용자가 알아서 기입하고, 추출한 dict만 받도록 합니다.

 

select_quote()로 랜덤한 글귀와 저자를 골라 리턴해 author, text로 보낸 후, 나머지는 상단에 smtplib를 소개했을 때 사용했던 코드를 거의 그대로 가져와 사용합니다. 코드를 실행시켜 보면, 아래 사진처럼 잘 작동합니다.

 

image

잘 작동한 결과물

 

부록

참고문헌


[python] strip().split() 사용하여 데이터 전처리 하는법 (tistory.com)

반응형