python 使用企业微信发邮件加加图形化界面

发布时间 2023-05-17 11:28:03作者: 老运维
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QTextEdit, QPushButton
import requests, base64, hashlib
import smtplib
import os
import glob
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import configparser
from PIL import Image
from email.mime.image import MIMEImage

config = configparser.ConfigParser()
config.read('config.ini')
html_content = """<style class="fox_global_style">
			div.fox_html_content { line-height: 1.5;}
			/* 一些默认样式 */
			blockquote { margin-Top: 0px; margin-Bottom: 0px; margin-Left: 0.5em }
			ol, ul { margin-Top: 0px; margin-Bottom: 0px; list-style-position: inside; }
			p { margin-Top: 0px; margin-Bottom: 0px }
		</style><div style="font-size: 14.6667px;" data-mail-from="wemail-pc"><div><div style="background-color:rgb(255, 255, 255)"><table cellpadding="0" cellspacing="0" data-table-source="wemail-sign" style="background-color: transparent; font-family: Verdana, arial, -apple-system, BlinkMacSystemFont, "PingFang SC", 苹方-简, "Microsoft YaHei", 微软雅黑, sans-serif;"><tbody><tr><td><div o-height="133"><table cellpadding="0" cellspacing="0" width="589" height="133" data-table-source="wemail-sign"><tbody><tr><td><p style="font-size: 21px;">Jing Pan</p><p style="line-height: 22px;"></p><p style="line-height: 22px; margin-right: 0px; margin-bottom: 12px; margin-left: 0px;"><span style="font-size: 12px;">Product Specialist</span> | <span style="font-size: 12px;">Product</span></p><img src="https://oss.shaoke.com/logoidentity/LOGO-tag-blue.png" role="presentation" width="90" style="display: inline-block; height: 27px; width: 90px;" o-max-width="none" o-height="27.2031px" class="preview-hover"></td><td width="30"></td><td direction="vertical" width="1" style="border-bottom: none; border-left: 1px solid #272D4B; width: 1px;" class=" c-darkmode_borderlc_39-45-75-100_to_30-34-57-100"></td><td width="30"></td><td><div o-height="100"><table cellpadding="0" cellspacing="0" data-table-source="wemail-sign"><tbody><tr height="25"><td width="30"><div o-height="13"><table cellpadding="0" cellspacing="0" data-table-source="wemail-sign"><tbody><tr><td style="vertical-align: bottom;"><img src="https://oss.shaoke.com/logoidentity/phone-icon-2x.webp" width="13" style="background-color: #272d4b; height: 13px; width: 13px;" class="c-darkmode_bgc_39-45-75-100_to_28-32-53-100 preview-hover" o-max-width="none" o-height="13px"></td></tr></tbody></table></div></td><td><a style="font-size: 12px;" class=" c-darkmode_purec_0-0-0-100_to_3-3-3-100">0755-88604254</a>|</td></tr><tr height="25"><td width="30"><div o-height="13"><table cellpadding="0" cellspacing="0" data-table-source="wemail-sign"><tbody><tr><td style="vertical-align: bottom;"><img src="https://oss.shaoke.com/logoidentity/email-icon-2x.webp" width="13" style="background-color: #272d4b; height: 13px; width: 13px;" class="c-darkmode_bgc_39-45-75-100_to_28-32-53-100 preview-hover" o-max-width="none" o-height="13px"></td></tr></tbody></table></div></td><td style="padding: 0;"><a href="mailto:john.stone@shaoke.com" style="font-size: 12px;" class=" c-darkmode_purec_0-0-0-100_to_3-3-3-100" target="_blank" rel="noopener">jing.pan@shaoke.com</a></td></tr><tr height="25"><td width="30"><div o-height="13"><table cellpadding="0" cellspacing="0" data-table-source="wemail-sign"><tbody><tr><td style="vertical-align: bottom;"><img src="https://oss.shaoke.com/logoidentity/link-icon-2x.webp" width="13" style="background-color: #272d4b; height: 13px; width: 13px;" class="c-darkmode_bgc_39-45-75-100_to_28-32-53-100 preview-hover" o-max-width="none" o-height="13px"></td></tr></tbody></table></div></td><td style="padding: 0;"><a style="font-size: 12px;" class=" c-darkmode_purec_0-0-0-100_to_3-3-3-100" target="_blank" rel="noopener">www.shaoke.com</a></td></tr><tr height="25"><td width="30"><div o-height="13"><table cellpadding="0" cellspacing="0" data-table-source="wemail-sign"><tbody><tr><td style="vertical-align: bottom;"><img src="https://oss.shaoke.com/logoidentity/address-icon-2x.webp" width="13" style="background-color: #272d4b; height: 13px; width: 13px;" class="c-darkmode_bgc_39-45-75-100_to_28-32-53-100 preview-hover" o-max-width="none" o-height="13px"></td></tr></tbody></table></div></td><td style="padding: 0;"><span style="font-size: 12px;">25/F,Block A,No.1 World Plaza,Futian,Shenzhen,China</span></td></tr></tbody></table></div></td></tr></tbody></table></div></td></tr><tr><td><div o-height="108"><table cellpadding="0" cellspacing="0" style="width: 100%;" data-table-source="wemail-sign"><tbody><tr style="width: 589px; height: 15px;"><td height="15"></td></tr><tr style="width: 589px; height: 2px;"><td direction="horizontal" height="1" style="border-bottom: 1px solid #020659; border-left: none; width: 100%;" class=" c-darkmode_borderbc_2-6-89-100_to_2-5-67-100"></td></tr><tr style="width: 589px; height: 5px;"><td height="5"></td></tr><tr><td style="color: #999999; font-size: 10px; font-style: italic; max-width: 360px; text-align: justify;" class=" c-darkmode_purec_153-153-153-100_to_115-115-115-100">Disclaimer:The information contained in this message may be privileged and confidential.It is intended to be read only by the individual or entity to whom it is addressed or by their designee.If the reader of this message is not the intended recipient,you are on notice that any distribution of this message,in any form,is strictly prohibited.If you have received this message in error,please immediately notify the sender and delete or destroy any copy of this message.</td></tr></tbody></table></div></td></tr></tbody></table></div></div><div id="wemailsigcontent"><br><div><br></div><div><br></div></div></div>
"""


class WXWork_SMS:
    def __init__(self):
        self.headers = {"Content-Type": "text/html"}
        self.send_url = config['wecom']['webhook']  # 测试机器人webhook地址
        self.auth = ('Content-Type', 'application/json')

    def send_requests(self, send_data):
        res = requests.post(url=self.send_url, headers=self.headers, json=send_data, auth=self.auth)
        print(res.json())

    def send_msg(self, text):
        # 发送消息
        send_data = {
            "msgtype": "text",  # 消息类型,此时固定为news
            "text": {
                "content": text,
                "mentioned_list": eval(config['wecom']['@'])
            }
        }
        self.send_requests(send_data)

    def text_to_html(self, text):
        result = ''
        texts = text.split('\n')
        print(texts)
        for t in texts:
            result += '<p>' + t + '</p>'
        result = result + '<img src="cid:image1">'
        print(result)
        return result

    def get_png(self):
        result = None
        for file in glob.glob("*.png"):
            print(os.path.basename(file))
            result = os.path.basename(file)
        return result

    def mail(self, title, content):
        host_server = config['email']['host_server']  # 主机地址
        port = int(config['email']['port'])  # 端口
        # 发件人邮箱
        sender = config['email']['sender']
        # 发件人邮箱密码、授权码
        code = config['email']['code']
        # 收件人
        recipient = config['email']['recipient']
        recipient = eval(recipient)
        # 抄送
        duplicate = config['email']['duplicate']
        duplicate = eval(duplicate)
        # 准备邮件数据
        # 邮件标题
        mail_title = title
        # 内容
        mail_content = content
        # SMTP
        smtp = smtplib.SMTP_SSL(host_server, port)
        # 登录
        smtp.login(sender, code)
        # 发送
        msg = MIMEMultipart()
        print(mail_content)

        # This example assumes the image is in the current directory
        if self.get_png():
            file = self.get_png()
        else:
            img = Image.new("RGB", (640, 480), color="white")
            img.save("image.png")
            file = 'image.png'
        fp = open(file, 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()

        # Define the image's ID as referenced above
        msgImage.add_header('Content-ID', '<image1>')
        msg.attach(msgImage)

        text_content = MIMEText(self.text_to_html(mail_content), 'html', 'utf-8')
        msg.attach(text_content)
        html_content_part = MIMEText(html_content, 'html', 'utf-8')
        msg.attach(html_content_part)

        msg['Subject'] = mail_title
        msg['From'] = sender
        msg['To'] = ", ".join(recipient)
        msg['Cc'] = " ,".join(duplicate)

        recipient.extend(duplicate)
        # recipient=str(recipient)
        print(recipient)
        smtp.sendmail(sender, recipient, msg.as_string())
        smtp.quit()


class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'jing.pan@shaoke.com'
        self.left = 10
        self.top = 10
        self.width = 400
        self.height = 540
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # # Create a label
        label1 = QLabel('Email content', self)
        label1.move(20, 20)

        # Create a textbox
        textbox1 = QTextEdit(self)
        textbox1.move(20, 40)
        textbox1.resize(360, 140)

        # # Create a second label
        label2 = QLabel('Title', self)
        label2.move(20, 180)

        # Create a second textbox
        textbox2 = QTextEdit(self)
        textbox2.move(20, 200)
        textbox2.resize(360, 140)

        # Create a button in the window
        button = QPushButton('Submit', self)
        button.move(20, 450)
        # connect button to function on_click
        button.clicked.connect(lambda: on_click(textbox1.toPlainText(), textbox2.toPlainText()))
        # Show window
        self.show()


def on_click(textbox1_text: str, textbox2_text: str):
    print(f'Textbox 1 value: {textbox1_text}')
    sms = WXWork_SMS()
    sms.send_msg(textbox1_text)
    sms.mail(textbox2_text, textbox1_text)
    print(f'Textbox 2 value: {textbox2_text}')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

  配置文件

[email]
host_server = smtp.exmail.qq.com
port = 465
sender = lingzhi.zou@shaoke.com
code = XXXXXXX
recipient = ['lingzhi.zou@shaoke.com','']
duplicate = ['','2474538243@qq.com']

[wecom]
webhook = https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=7405390e-fdbe-44dd-8f9b-5fb5d0a6a93e
@ =  ['@all', 'joyce.yang@shaoke.com', 'cai.yihua@shaoke.com', 'Hu','marjorie.choi@shaoke.com']