[ Python ] smtplib를 이용해서 html 메일로 보내기

2019. 11. 24. 16:27분석 Python/구현 및 자료

728x90

도움이 되셨다면, 광고 한번만 눌러주세요.  블로그 관리에 큰 힘이 됩니다 ^^

가끔 이쁘게 결과를 만들어서 메일로 보내고 싶을 때가 있다.
이때 활용할 수 있는 패키지가 기본으로 제공하는 smtplib 라는 패키지가 있고, 이번에는 단순히 메세지만 보내는 것 아니라 html을 보내보고자 한다.

필자는 html을 따로 배우지 않고 기초정도만 아는 정도라 꾸미는 능력이 부족하지만, 
html에 대해 지식이 있으신 분은 그대로 사용할 수 있기 때문에 굉장히 편리하게 할 수 있을 것 같다.

일단 지메일로 이메일 보내는 것 자체는 https://data-newbie.tistory.com/309 블로그를 참고하시면 될 것 같다.

개인적으로 아직 로그인 없이 보내는 법을 알고 싶은데, 혹시 이 글을 읽고 있는 분 중에 아는 분이 있다면 댓글로 달아주셨으면 좋겠습니다.

하고자 하는 것 :  table 2개를 나란히 정렬해서 메일로 보내기

import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

Notebook의 이름을 가져오는 코드!

%%javascript
IPython.notebook.kernel.execute(`notebookName = '${window.document.getElementById("notebook_name").innerHTML}'`);

import numpy as np , re
import pandas as pd
html_ = pd.DataFrame(np.random.normal(size = (10,4)),
                     columns = list("ABCD"), 
                    ).to_html(index = False )
html_1 = re.sub("\n", "",html_)
html_ = pd.DataFrame(np.random.normal(size = (10,4)),
                     columns = list("가나다라"), 
                    ).to_html(index = False )
html_2 = re.sub("\n", "",html_)
# border-collapse: separate;
# border-spacing: 1px;
#     padding: 10px;
pre =\
"""
<html>
<head>
<style>
.ft-default-1 { font-size: 24px; }
.ft-default-2 { font-size: 32px; }
.ft-smaller { font-size: smaller; }
.ft-larger { font-size: larger; }
table {
    width : 90%;
    text-align: center;
    line-height: 1.5;
    margin: 3px 3px;
}
table th {
    width: 155px;
    padding: 10px;
    font-weight: bold;
    text-align: center;
    vertical-align: top;
    color: #fff;
    background: #ce4869 ;
}
table td {
    width: 155px;
    vertical-align: top;
    text-align: center;
    border-bottom: 1px solid #ccc;
}
</style>
</head>
<center><span class="ft-default-2">""" + """{}</span></center>""".format(notebookName)
first = '<div style="width:50%;float:left;"><table id="tbl1"><caption class="ft-default-1">{}</caption>{}</table></div>'.format("Alphabet" , html_1)
second = '<div style="width:50%;float:right;"><table id="tbl2"><caption class="ft-default-1">{}</caption>{}</table></div>'.format("한글", html_2)
sendHtml = '{}<body><div>{}{}</div></body></html>'.format(pre , first , second)
sender_email = '####@gmail.com' #'‘sendermail@example.com’       # 송신 메일
receiver_email = '####@gmail.com'        # 수신 메일

msg = MIMEMultipart('Test')
msg['Subject'] = "Send 제목 Html"
msg['From'] = sender_email
msg['To'] = receiver_email
text = "이것의 기능은?"
part2 = MIMEText(sendHtml, 'html')
# part1 = MIMEText(text, 'plain')
# msg.attach(part1)
msg.attach(part2)

위의 코드처럼 하면 일단 보낼 부분에 대해서 틀을 만든 것이다!

login = '####@gmail.com'
password = '@@@@@'
with smtplib.SMTP_SSL("smtp.gmail.com") as server:
    server.login(login, password)
    server.sendmail(sender_email,
                    receiver_email,
                    msg.as_string())
print('Sent') 

이제 보낸 결과를 확인해보자!

자 이런식으로 결과를 보낼 수가 있다!!

 

pandas에서 to_html이라는 기능이 있어서 일단 편하게 table을 만들 수 있고,
html 문법 중 style에 대해서 조금 밖에 이해를 못했지만, 이런식으로 이쁘게 꾸며서 보낼 수가 있다!

 

728x90