728x90
반응형
파이썬 'smtplib' 를 통해 메일을 보낼 수 있다.
cron을 통해 특정주기마다 반복적으로 메일을 보내는 방법을 소개한다.
import smtplib
import re
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
html_content = """
<html>
<head></head>
<body>
<p>
파이썬 코드로 메일 보내기
</p>
</body>
</html>
"""
def send_mail(addr):
reg = "^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$" # 유효성 검사
if re.match(reg, addr):
smtp.sendmail(my_account, to_mail, msg.as_string())
print("정상적으로 메일이 발송되었습니다.")
else:
print("받으실 메일 주소를 정확히 입력하십시오.")
# smpt 연결
gmail_smtp = "smtp.gmail.com"
gmail_port = 465
smtp = smtplib.SMTP_SSL(gmail_smtp, gmail_port)
# login
my_account = "보낼메일 주소"
my_password = "패스워드"
smtp.login(my_account, my_password)
# to
to_mail = "받을메일 주소"
# info
msg = MIMEMultipart()
msg["Subject"] = "메일 제목"
msg["From"] = my_account
msg["To"] = to_mail
# content
content_part = MIMEText(html_content, "html")
msg.attach(content_part)
# attach
file = "파일경로" # 절대경로 혹은 상대경로
with open(file, 'rb') as attachment:
part = MIMEApplication(attachment.read(), Name = "첨부파일 이름")
part['Content-Disposition'] = 'attachment; filename = "첨부파일 이름"
msg.attach(part)
send_mail(to_mail)
smtp.quit()
위 코드는 간단하게 메일을 보낼 수 있는 예시이다.
첨부파일을 사용하기 위해 'from eamil.mime.application import MIMEApplication' 을 임포트 하고 작성한다.
로그인에 필요한 메일 패스워드는 기존에 우리가 알던 로그인할때 필요한 패스워드가 아닌 앱 비밀번호로 구글 설정에 들어가서 확인해야한다.
https://myaccount.google.com/security 링크 접속 > 2단계인증 > 하단에 앱 비밀번호 설정 > 앱 비밀번호 생성 > 생성된 키 사용