[Python] SMTP로 이메일 보내기

주소록에 있는 형태로 SMTP로 이메일을 자동으로 보내는 코드 

import smtplib
from email.mime.text import MIMEText

SUBJECT = ""
FROM = ""
ID = ""
PW = ""

smtp = smtplib.SMTP("smtp.naver.com", 587)

smtp.ehlo()
smtp.starttls()
smtp.login(ID, PW)

f = open("본문.txt", mode="r", encoding="utf-8")
bonmun = f.read()

with open("통합_주소록.csv", mode="r", encoding="utf-8") as j:
    jusorok = j.readlines()
    for juso in jusorok:
        split_juso = juso.split(",")
        new_bonmun = bonmun.format(split_juso[0])
        to = split_juso[1]

        msg = MIMEText(new_bonmun)
        msg["Subject"] = SUBJECT
        msg["From"] = FROM
        msg["To"] = to

        smtp.sendmail(FROM, to, msg.as_string())

smtp.quit()

주소록 형식

이름,이메일@도메인.com
이름2,이메일@도메인.com
...

아래는 주소록 여러 개를 통합 및 중복 제거를 실행하는 코드

jusorok = list()
file_names = ["2020_4월_문학팀_주소록.csv", "2024_경학팀_주소록.csv", "2024_문학팀_주소록.csv"]

for file_name in file_names:
    print(file_name)
    with open(file_name, mode="r", encoding="utf-8") as f:
        jusos = f.readlines()
        for juso in jusos:
            split_juso = juso.strip().split(",")
            if split_juso[1] != "": jusorok.append(split_juso) 

jusorok.sort()
dedup = [jusorok[i] for i in range(len(jusorok)) if i == 0 or jusorok[i] != jusorok[i-1]]
print(dedup)
with open("통합_주소록.csv", mode="w", encoding="utf-8") as file:
    for juso in dedup:
        file.write(",".join(juso))
        file.write("\n")

네이버에서 사용하기 위해서는 아래 설정이 필요하다.


필요한 정보는 위 페이지 하단에 있는 내용을 참고하면 된다.

또한, 네이버 2단계 인증을 사용하고 있다면 비밀번호를 옳게 입력해도 틀렸다고 나올 건데(username and password not accepted), 이 경우 아래 사진과 같이 2단계 인증 관리 페이지에서 애플리케이션 비밀번호를 신규 발급받아 사용하면 된다.





댓글

이 블로그의 인기 게시물

[몬스터헌터 와일즈] 광룡증을 알아보자 (feat. 흑식일체, 무아지경, 식공복장)

[엘든 링 밤의 통치자] 집행자 요도(히나타츠카미) 유물 분석

[몬스터헌터 와일즈] 역습을 알아보자