python 发送邮件功能

import logging
import smtplib
import time
import traceback
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from io import StringIO

import pandas as pd

from counter import StatisticsClientData
from pub import yesterday, the_day_before_yesterday, today, weekday, month_firstday, which_month

LOG_FORMAT = “%(asctime)s - %(levelname)s - %(message)s”
logging.basicConfig(filename=‘email.log’, level=logging.DEBUG, format=LOG_FORMAT)

class ClientSendEmail(object):
    def __init__(self):
        self.fromaddr = "xxx"
        self.smtpaddr = "smtp.exmail.qq.com"
        self.toaddrs = ["xxx"]
        self.ccaddrs = ['XXX']
        self.password = "密码"

    @property
    def subject(self):
        return yesterday() + '数据统计'

    def sendmail(self):
        '''''
        @subject:邮件主题
        @msg:邮件内容
        @toaddrs:收信人的邮箱地址
        @fromaddr:发信人的邮箱地址
        @smtpaddr:smtp服务地址,可以在邮箱看,比如163邮箱为smtp.163.com
        @password:发信人的邮箱密码
        '''
        t0 = time.time() * 1000
        myhtml = self.standard_email_format()
        mail_msg = MIMEText(myhtml, 'html', 'utf-8')
        content = MIMEText('<html><body><img src="cid:imageid" alt="imageid"></body></html>', 'html', 'utf-8')
        msgAlternative = MIMEMultipart('alternative')
        msgAlternative.attach(mail_msg)
        msgAlternative.attach(content)
        with open("picture.png", "rb") as file:
            img_data = file.read()
        img = MIMEImage(img_data)
        img.add_header('Content-ID', 'imageid')
        msgAlternative.attach(img)
        msgAlternative['Subject'] = self.subject
        msgAlternative['From'] = self.fromaddr
        msgAlternative['To'] = ','.join(self.toaddrs)
        msgAlternative['Cc'] = ','.join(self.ccaddrs)
        try:
            s = smtplib.SMTP()
            s.connect(self.smtpaddr)  # 连接smtp服务器
            s.login(self.fromaddr, self.password)  # 登录邮箱
            s.sendmail(self.fromaddr, self.toaddrs, msgAlternative.as_string())  # 发送邮件
            s.quit()
            t1 = time.time() * 1000
            logging.info(today() + " 邮件已经发送完毕, 用时: " + str(t1 - t0))
        except Exception as e:
            logging.error("Error: unable to send email, the time is " + today())
            logging.error("error detail for " + str(e))
            logging.error(traceback.format_exc())

	    def api_ratio(self, who, total):
	        # 当日调用占比, 以及有效调用占比
	        if not total:
	            decimal = who / 1
	        else:
	            decimal = who / total
	        return '%.d%%' % (decimal * 100)
	
   def standard_email_format(self):
        app_ke1 = "sfdgdfcfv"  # 相当于user_id 用户身份标识
        app_ke2 = 'ffbdcxc'
        app_ke3 = 'dsvfgr'
        app_list = [app_opp, app_vv, app_hw]

        client = StatisticsClientData()
        date = yesterday()
        current = client.current_date_total_data(appidlist=app_list, date=date)
        current_valid = client.current_date_valid_data(appidlist=app_list, date=date)
        total = client.total_data(appidlist=app_list, date=date)
        total_valid = client.total_valid_data(appidlist=app_list, date=date)

        before_client_data = client.before_day_data(the_day_before_yesterday())
        current_times = current[0] + current[1] + current[2]
        current_times_valid = current_valid[0] + current_valid[1] + current_valid[2]
        #
        buffer = StringIO()
        df_d = {'手机型号': ["ke1", 'ke2', 'ke3'], "调用接口": ["api_name"] * 3,
                "当日调用次数": self.three_client_format_data(current[0], current[1], current[2]),
                "当日调用占比": [self.api_ratio(current[0], current_times),
                           self.api_ratio(current[1], current_times),
                           self.api_ratio(current[2], current_times)],
                '当日有效调用次数': self.three_client_format_data(current_valid[0], current_valid[1], current_valid[2]),
                '当日有效调用占比': [self.api_ratio(current_valid[0], current_times_valid),
                             self.api_ratio(current_valid[1], current_times_valid),
                             self.api_ratio(current_valid[2], current_times_valid)],
                '累计调用次数': self.three_client_format_data(total[0], total[1], total[2]),
                '累计有效调用次数': self.three_client_format_data(total_valid[0], total_valid[1], total_valid[2]),
                '日调用环比': [self.api_ratio(current[0], before_client_data[0]),
                          self.api_ratio(current[1], before_client_data[1]),
                          self.api_ratio(current[2], before_client_data[2])]}
        week = []
        if weekday():
            wk_l = client.weekly_data_statistic(app_list, before=1)  # 上周数据
            wk_b = client.weekly_data_statistic(app_list, before=2)  # 上上周数据
            wklist = [self.api_ratio(wk_l[i], wk_b[i]) for i in range(len(wk_l))]
            week.append(self.handle_list(wk_l))
            week.append(self.handle_list(wk_b))
            df_d.update({'周调用环比': wklist})
        month = []
        if month_firstday():
            month_l = client.monthly_data_statistic(appid_list=app_list)
            month_b = client.monthly_data_statistic(date=which_month(last=1), appid_list=app_list)
            monthlist = [self.api_ratio(month_l[i], month_b[i]) for i in range(len(month_l))]
            month.append(self.handle_list(month_l))
            month.append(self.handle_list(month_b))
            df_d.update({'月调用环比': monthlist})
        client.save_into_mongo(current[0], current_valid[0], current[1], current_valid[1], current[2], current_valid[2],
                               week=week, month=month)
        df = pd.DataFrame(df_d)
        df.to_html(buffer, index=False, border='1px solid black')
        return buffer.getvalue()

    def handle_list(self, ll):
        data_dict = {}
        client = ['ke1', 'ke2', 'ke3']
        for key, value in zip(client, ll):
            data_dict[key] = value
        return data_dict

    def three_client_format_data(self, counter1, counter2, counter3):
        # 三个数据格式化 ----三家
        return [self.fomat_float(counter1), self.fomat_float(counter2), self.fomat_float(counter3)]

    def fomat_float(self, counter):
        # 数据格式化 --- 123,235
        return f"{counter:,d}"
        # return "{:,}".format(counter)


if __name__ == '__main__':
    ClientSendEmail().sendmail()
    # cc = ClientSendEmail().handle_list([1, 2, 3])
    # print(cc)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值