首页 > 编程语言 >python 使用企业微信发邮件加加图形化界面

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

时间:2023-05-17 11:35:50浏览次数:42  
标签:加加 python text self send content import recipient 图形化

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:[email protected]" style="font-size: 12px;" class=" c-darkmode_purec_0-0-0-100_to_3-3-3-100" target="_blank" rel="noopener">[email protected]</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 = '[email protected]'
        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 = [email protected]
code = XXXXXXX
recipient = ['[email protected]','']
duplicate = ['','[email protected]']

[wecom]
webhook = https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=7405390e-fdbe-44dd-8f9b-5fb5d0a6a93e
@ =  ['@all', '[email protected]', '[email protected]', 'Hu','[email protected]']

 

标签:加加,python,text,self,send,content,import,recipient,图形化
From: https://www.cnblogs.com/huluxia-fun/p/17408074.html

相关文章

  • generate a 3D chart in Python using the CSV data
    Here's an example of how you could use Matplotlib to create a 3D scatter plot from your CSV data:   importpandasaspdimportmatplotlib.pyplotaspltfrommpl_toolkits.mplot3dimportAxes3D#LoadtheCSVdataintoaPand......
  • 用Python开发输入法后台
    首先,安装PIME,github地址:https://github.com/EasyIME/PIME下载安装PIME-1.3.0-stable-setup.exe,就可以得到一个输入法,后端是python,在安装目录下‘C:\ProgramFiles(x86)\PIME\’,python目录就是运行脚本。入口点是'server.py',其中安装目录下的‘PIMELauncher.exe’是负责前后台......
  • python 项目报错 Fatal Python error: _enter_buffered_busy: could not acquire lock
    FatalPythonerror:_enter_buffered_busy:couldnotacquirelockfor<_io.BufferedWritername=''>atinterpretershutdown,possiblyduetodaemonthreadsPythonruntimestate:finalizing(tstate=0x00005654c4008a40)Currentthread0x00007fc......
  • Python学习
    3-13字符串类型字符串类型:str   1.定义格式:       变量='内容'           打印一行       变量="内容"           打印一行       变量='''内容'''或者三引号           可以通过回车的方式换行,且打印出......
  • python环境搭建,使用conda工具
    开发环境搭建安装miniConda:conda和miniConda和Anaconda的区别安装pycharm:pycharm创建项目并使用base环境作为开发环境pycharm的interpreter是什么安装jupyter:jupyter的快捷键conda的虚拟环境命令:condacreatecondaact......
  • 局部添加加载中效果loading (vue+elementUI)
    产品需求:有时候我们不想为整个页面添加loading效果。只想给局部区域添加loading效果。(这效果就不揍产品了)在一个表格数据加载时,因为需要连接其它东西,所以后台接口返回数据需要较长时间,因此添加局部Loading效果,增加用户体验度,最开始使用下面代码,直接放到<el-table>中,测试......
  • 基于”python+requests模块“接口自动化的基本方法使用
    1,接口自动化测试1.1概念接口测试:是对系统或者组件之间的接口进行测试,主要是校验数据的交换,传递和控制管理过程,以及相互逻辑依赖关系。接口自动化测试:让程序代替人为对接口项目进行自动验证测试的过程1.2实现方式1,工具(jmeter,postman)2,代码(python-requests)1.3测试工具缺点......
  • python中提供正则支持的re模块
    1re模块的作用个人觉得就是按照给定的条件,在文本中去寻找匹配对应的字符re模块十分强大,提供的正则规则也非常多,网上有很多辅助和测试工具,现在有ai就更加方便了,不过一些基础的使用最好还是了解下2正则表达式个人理解,正则表达式就是寻找、匹配的规则或者条件,它是一个字符串的......
  • Python学习之十三_pip的学习
    Python学习之十三_pip的学习pip的含义pip:pipisthepackageinstallerforPython.YoucanusepiptoinstallpackagesfromthePythonPackageIndexandotherindexes.pip其实就是python的包管理器:PackagesInstallforPython他可以在线安装也可以离线安装......
  • Python: 结合多进程和 Asyncio 以提高性能
    动动发财的小手,点个赞吧!简介多亏了GIL,使用多个线程来执行CPU密集型任务从来都不是一种选择。随着多核CPU的普及,Python提供了一种多处理解决方案来执行CPU密集型任务。但是直到现在,直接使用多进程相关的API还是存在一些问题。在本文开始之前,我们还有一小段代码来帮助演......