[ Python ] smtplib을 활용한 메일 보내기 (이미지 , 텍스트 , gif)

2020. 1. 5. 15:09분석 Python/구현 및 자료

728x90

Please Click my Ads :) 

도움이 되셨다면, 광고 한 번만 눌러주세요! 블로그 운영에 큰 힘이 됩니다!  :)

학습이 완료되고 나서 log 같은 것을 확인하고 그래야 하는데, 이러면 역시 귀찮을 수 있기 때문에 완료되면 메일로 보내기로 만들어 봤다.
그래서 결과물로 저장하는 image와 log file을 gmail로 보내는 것을 구현해봤다.
파이썬에서 메일로 보낼 때 참고하시면 될 것 같다!

import os , re
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import codecs
### Login Information
login = '#####@gmail.com'
password = '#######'
sender_email = login
receiver_email = login
msg = MIMEMultipart('SendMail')
msg['Subject'] = "Train Complete"
msg['From'] = sender_email
msg['To'] = receiver_email
text = "학습 완료! 체크!"
part2 = MIMEText(text)
msg.attach(part2)
### Send Images
static = os.getcwd()
### Send img
img_path = [os.path.join(static, i) for i in os.listdir(static) if re.search("NN_" , i ) ]
for ImgFileName in img_path :
    img_data = open(ImgFileName, 'rb').read()
    image = MIMEImage(img_data, name=os.path.basename(ImgFileName))
    msg.attach(image)    
### Send txt    
filename = os.path.join(static ,"tf_log.txt" )
f = codecs.open(filename, 'rb', 'utf-8')
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename="tf_log.txt")           
msg.attach(attachment)
### Send Gif
f = codecs.open("abc.gif", 'rb')
attachment = MIMEImage(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename="abc.gif")           
msg.attach(attachment)
with smtplib.SMTP_SSL("smtp.gmail.com") as server:
    server.login(login, password)
    server.sendmail(sender_email,
                    receiver_email,
                    msg.as_string())
print('Sent') 

결과물

728x90