본문 바로가기
Python

파이썬 메일 전송시 파일 첨부

by 앗사비 2022. 8. 4.
728x90
import smtplib
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 
from email.mime.base import MIMEBase
from email import encoders

# 변수값
gmail_id = 'test@test.com'
gmail_pw = '...'
mail_to = 'test@test.com'
subject = '리포트'
file_path = './data/'
file_name = 'test.xlsx'

# 메일 코드
msg = MIMEMultipart()
# msg['From'] = email_user
msg['To'] = mail_to
msg['Subject'] = subject
# body = '' # 본문
# msg.attach(MIMEText(body,'plain'))
file=file_path+file_name
attachment  =open(file,'rb')
part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+file_name)
msg.attach(part)
text = msg.as_string()
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.starttls()
smtp.login(gmail_id,gmail_pw)
smtp.sendmail(gmail_id,mail_to,text)
smtp.quit()
728x90