python(十)邮件处理

一、知识点

二、应用

1、脚本:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 
# @Author  : 
# @Site    :
# @File    : gmail.py
# @Software: PyCharm

import os
import traceback
import smtplib
import mimetypes
from email import encoders
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from exchangelib import Account, Credentials, FaultTolerance, HTMLBody

class Mail:
    def __init__(self,user = "",password="",signtxt="",host=""):
        if isinstance(user, dict):
            self.user = user.get("user")
            self.password = user.get("password")
            self.signtxt = user.get("signtxt","")
            self.host = user.get("host")
        elif isinstance(user, str) and user != "":
            self.user = user
            self.password = password
            self.signtxt = signtxt
            self.host = host


    def send_email(self,to_list, title, content_text, attachment_list=[], cc_list="", codetype="gb2312"):
        '''
        to_list: 收件人列表,以逗号隔开,如:[email protected],[email protected]
        title: 邮件标题
        content_text: 邮件正文
        attachment_list: 邮件附件,数组列表类型,如:["c:\\test.txt"]
        cc_list: 炒送人列表,以逗号隔开,跟收件人列表格式一样
        codetype:附件编码,文本一般不用修改,其他多媒体格式需要修改
        '''
        # 初始化发件人信息
        # 生成邮件体
        msg = MIMEMultipart()
        msg["subject"] = title
        msg["to"] = to_list
        msg["from"] = self.user
        msg["cc"] = cc_list

        # 添加附件
        index = 0
        for att in attachment_list:
            ctype, encoding = mimetypes.guess_type(att)
            if ctype is None or encoding is not None:
                # No guess could be made, or the file is encoded (compressed), so
                # use a generic bag-of-bits type.
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            print(maintype, subtype)
            attcontent = None
            if maintype == "text":
                fp = open(att,'r', encoding='UTF-8')
                # Note: we should handle calculating the charset
                attcontent = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == "image":
                fp = open(att, "rb")
                attcontent = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == "audio":
                fp = open(att, "rb")
                attcontent = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(att, "rb")
                attcontent = MIMEBase(maintype, subtype)
                attcontent.set_payload(fp.read())
                fp.close()
            # Encode the payload using Base64
            encoders.encode_base64(attcontent)
            # Set the filename parameter
            attcontent.add_header("Content-Disposition", "attachment", filename=os.path.split(att)[1])
            attcontent.add_header("Content-ID", "<%d>" % index)
            attcontent.add_header("X-Attachment-Id", "%d" % index)
            msg.attach(attcontent)
            index += 1

        # 邮件正文
        content = MIMEText(content_text + self.signtxt, "html", "utf-8")
        msg.attach(content)

        # 登录邮箱发送邮件内容
        try:
            print("开始发送邮件:" + title)
            server = smtplib.SMTP(self.host)
            # server.connect(self.host)
            server.starttls()
            server.login(self.user, self.password)
            server.sendmail(msg["from"], msg["to"].split(",") + msg["cc"].split(","), msg.as_string())
            server.quit()
            print("发送邮件成功!")
        except Exception as e:
            log.error(e)
            traceback.print_exc()
        return

    def receive_email(self):
        '''
        获取收邮件的账户,类型是exchanglib中的Account
        '''
        # 连接到POP3服务器
        credentials = Credentials(self.user, self.password)
        account = Account(self.user, credentials=credentials, autodiscover=True)
        return account

def convert_list_to_html(datas,titles=None):
    """
        描述:将列表转成HTML格式
        datas : 列表数据[[...],[...],[...]]
        titles : 列标题
    """
    if titles is None:
        titles = []
    if datas and len(datas) > 0:
        html = "<table border='1' cellpadding='10'>"
        row = datas[0]
        # [[...],[...]...] 这种形式的数组
        if type(row).__name__ == 'dict':
            html += "<tr bgcolor='LightBlue'>"
            if len(titles) == 0:
                if datas and len(datas) > 0:
                    row = datas[0]
                    for k in row:
                        titles.append(k)
            for title in titles:
                html += "<th>" + title + "</th>"
            html += "</tr>"
            for row in datas:
                html += "<tr>"
                for k in titles:
                    html += "<td>" + str(row.get(k, "")) + "</td>"
                html += "</tr>"
            html += "</table>"
            return html
        # [{...},{...}...] 这种形式的数组
        elif type(row).__name__ == "list":
            html += "<tr bgcolor='LightBlue'>"
            if len(titles) > 0:
                for title in titles:
                    html += "<th>" + title + "</th>"
            else:
                for index, item in enumerate(row):
                    html += "<th>col" + str(index+1) + "</th>"
            html += "</tr>"
            for row in datas:
                html += "<tr>"
                for item in row:
                    html += "<td>" + str(item) + "</td>"
                html += "</tr>"
            html += "</table>"
            return html
    else:
        return ""


if __name__ == "__main__":
    mail = Mail({
    
    
        "host" : "smtp.qq.com",
        "user" : "发件人邮箱",
        "password" : "发件人邮箱密码"
      })

    datas = [['001','张三'],['002','李四']]
    titles = ['学号','姓名']
    body = convert_list_to_html(datas,titles)
    mail.send_email(to_list = "收件人邮箱",title = "测试",content_text = "hello world",attachment_list = ['C:\\Users\\XXUZ\\Desktop\\1.xlsx'])
    mail.send_email(to_list = "收件人邮箱",title = "测试",content_text = body,attachment_list = ['C:\\Users\\XXUZ\\Desktop\\1.csv'])

    #account = mail.receive_email()
    #mail_items = []
    #for item in account.inbox.filter(subject__contains="测试").filter(subject__contains="20211122").filter(subject__contains="鑫利"):
    #    mail_items.append(item)
    #
    #for item in mail_items:
    #    print(item.subject)

2、执行结果:
在这里插入图片描述

在这里插入图片描述

三、参考资料

猜你喜欢

转载自blog.csdn.net/shammy_feng/article/details/121470295