smtplib發郵件

 

dataframe轉html(且dataframe中含圖片) ,smtplib利用qq郵箱授權代發郵件

# smtplib_mail.py

# -*- coding:utf-8 -*-
import smtplib
import configparser
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from datetime import datetime, timedelta
import pandas as pd
import pandas.io.formats.style

config = configparser.RawConfigParser()
config.read('config.ini', encoding='UTF-8')


def send_mail(id_list, df, mail_type):
    # 設置服務器所需信息
    fromaddr = config['email']['fromaddr']  # 郵件發送方郵箱地址
    password = config['email']['password']  # 密碼(部分郵箱爲授權碼)
    toaddrs = config['email']['to_list'].split(',')  # 郵件接受方郵箱地址,多個郵件地址需要[]

    dt = str(datetime.now() + timedelta(days=-1))[0:10]  # 取昨日日期爲郵件標題命名

    message = MIMEMultipart('related')
    if mail_type == 'abnormal_result':
        message['Subject'] = dt + '測試郵件名1'
    else:
        message['Subject'] = dt + '測試郵件名2'  # 郵件主題
    message['From'] = '佚名'  # 發送方信息
    message['To'] = ", ".join(toaddrs)  # 接受方信息
    
    html_msg = df_to_html(df)
    msg_text = MIMEText(html_msg, _subtype='html', _charset='utf-8')
    message.attach(msg_text)

    # 我發的郵件的表格中有圖片
    for machine_id in id_list:
        fp = open(str(machine_id) + '.png', 'rb')
        img = MIMEImage(fp.read())
        img.add_header('Content-ID', str(machine_id))
        message.attach(img)

    # 登錄併發送郵件
    try:
        server = smtplib.SMTP('smtp.qq.com')  # qq郵箱服務器地址
        server.login(fromaddr, password)
        server.sendmail(fromaddr, toaddrs, message.as_string())
        print('****** send mail success ******')
        server.quit()
    except smtplib.SMTPException as e:
        print('error', e)  # 打印錯誤


def df_to_html(df):
    # df轉線寬正常的html表格
    result = '''
<html>
<head>
<style>
    h2 {
        text-align: center;
        font-family: Helvetica, Arial, sans-serif;
    }
    table { 
        margin-left: auto;
        margin-right: auto;
    }
    table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
    }
    th, td {
        padding: 5px;
        text-align: center;
        font-family: Helvetica, Arial, sans-serif;
        font-size: 90%;
    }
    table tbody tr:hover {
        background-color: #dddddd;
    }
    .wide {
        width: 90%; 
    }

</style>
</head>
<body>
    '''
    if type(df) == pd.io.formats.style.Styler:
        result += df.render()
    else:
        result += df.to_html(classes='wide', escape=False)

    result += '''
</body>
</html>
'''
    return result

 

配置文件: 

# config.ini

[email]
fromaddr = 授權發件的郵箱(如[email protected])
password = 這裏填授權碼
to_list = [email protected],[email protected],[email protected]

參考文章:https://www.cnblogs.com/insane-Mr-Li/p/9121619.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章