您的位置:首页 > 编程语言 > Python开发

Python 骚操作--邮件转微信

2021-04-05 23:06 921 查看

在日常工作中,我们会经常收到邮件,有些是重要的邮件我们希望第一时间知晓,如领导发送的邮件,程序报警邮件。微信是我们使用频率最高的 app 了,因此如果能把邮件内容及时发送到微信,我们就可以及时获取邮件信息,进而采取相应行动。比打开邮件客户端再点击邮件查看要方便多了。

需要安装第三方库 wxpy,wechat_sender,zmail

pip install wxpy
pip install wechat_sender
pip install zmail

原理:使用 wxpy 登陆网页版微信,使用 wechat_sender 监听 wxpy 登陆的微信,使用 zmail 获取邮件。

思维导图如下:

完整代码
文件一 :startWechat.py

# -*- coding: utf-8 -*-
from wxpy import *
from wechat_sender import listen

#扫码登陆网页版微信
bot = Bot(cache_path=True)

@bot.register(Friend)
def save_msg(msg):
   tuling.do_reply(msg)  # 机器人自动回复
   print(msg, file=open("./saved.txt", "a"))  # 保存所有朋友的消息

# 响应好友请求
@bot.register(msg_types=FRIENDS)
def new_friend(msg):
   user = msg.card.accept()  # 接受好友请求
   user.set_remark_name(
       msg.text.replace("我是", "").replace("我", "").replace(" ", "")
   )  # 自动添加备注

listen(bot) #监听

请执行 python startWechat.py  并扫二维码登陆微信,并让它持续运行。

文件二:SendMail2wechat.py

from wechat_sender import Sender
import zmail
import time

mail_user = "******@xxx.com"
mail_pwd = "******"
mail_host = "mail.wjrcb.com" # eg: pop3.163.com 主流邮件服务器,这个不传此参数

server = zmail.server(mail_user, mail_pwd, pop_host = mail_host)
mail = server.get_latest()
id = mail["id"] - 1

while True:
   try:
       mail = server.get_latest()
       maxid = mail["id"]
       while id < maxid:
           id += 1
           mail = server.get_mail(id)
           # 主题 + 正文
           content = "".join(mail["content"]) if mail["content"] != [] else "".join(
               mail["content_html"]
           )
           message = f"""发件人:\n{mail['from']}\n主题:\n{mail['subject']}\n正文:\n{content}"""
           send_ip = mail["raw"][17].decode("utf-8").split(":")[1].replace(" ", "")
           Sender().send(message)
       # 如果邮箱有邮件被删除
       if id > maxid:
           id = maxid
   # 如果超时,则重新登陆
   except Exception as e:
       server = zmail.server(mail_user, mail_pwd, pop_host =  mail_host)
   # 每30秒检查一次
   time.sleep(30)

运行 python SendMail2wechat.py,消息会自动发送至文件传输助手,当然也可以自己调,详见 wechat_sender 的文档。 体现一下效果吧!


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: