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 = '''





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

    result += '''


'''
    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

你可能感兴趣的:(Python,项目)