使用Python实现自动发送日报给微信群(附代码)
目录
每天需要发日报文件到微信工作群。能不能刚自动python脚本完整这个工作解放双手。
目标:每天自动将日报文件及日报摘要发送到微信工作群中。 目前日报的处理已经基于Python实现自动取数并发送邮件, 导入smtplib ,email库 设置eamil信息,添加一个MIMEmultipart类,处理正文及附件
python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import encoders
import time
#设置登录及服务器信息
receivers = ['Email add 1 ','Email add 2']
sender = 'xxx @ xxx.com'
# 请在邮件服务商中查找,126企业邮为此串;
mail_host = 'smtp.126.com',
# 密码
mail_pass = ''
def sendmails(subject,receivers):
#设置eamil信息
#添加一个MIMEmultipart类,处理正文及附件
message = MIMEMultipart()
message['From'] = sender
message['To'] = receivers[0]
#邮件标题
message['Subject'] = subject
# 邮件正文,当然也可以写在一个文本文件中,读取进来。
e_content = '您好! \n 附件是…… \
'\n祝顺利!' \
'\n \n \n----- \n如有问题…'
message.attach(MIMEText(e_content, 'plain', 'utf-8'))
att1 = MIMEText(open(file_path + file_name, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
#att1["Content-Disposition"] = "attachment;filename=" + ('gbk','',file_name)
att1.add_header('Content-Disposition', 'attachment', filename=('gbk', '', filename))
# gbk,以及encoders可以降低附件名称出现乱码的概率,但在outlook中查看附件时仍可能出现乱码。
encoders.encode_base64(att1)
message.attach(att1)
#登录并发送
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host,25)
smtpObj.login(sender,mail_pass)
smtpObj.sendmail(
sender,receivers,message.as_string())
print('success')
smtpObj.quit()
except smtplib.SMTPException as e:
print('error',e)
现在我们希望更进一步,同时自动发送到微信群,这样整个过程就实现了100%的自动化。 那如何使用Python发送微信消息呢,这个也很简单,我们借助第三方工具包来实现:
python
# 导入工具包
from wxauto import WeChat
import time
# 给单人发送消息
to = "文件传输助手" # 要发送的人
msg = "今天的日报请查收:" # 要发送的消息
file = "D:\Documents\2023-01-21.xls" # 要发送的文件
wx = WeChat() # 获取当前微信客户端
wx.Search(to) # 打开聊天窗口
wx.SendMsg(msg) # 发送消息
wx.SendFiles(file) # 发送文件
print("发送结束!")
# 给多人发送消息
to_names = ["文件传输助手", "运营组", "产品组"] # 要发送的人或群
file = "D:\Documents\2023-01-21.xlsx" # 要发送的文件
msg = "今天的日报请查收:" # 要发送的消息
wx = WeChat() # 获取当前微信客户端
for to in to_names:
time.sleep(3) # 等待3秒
wx.Search(to) # 打开聊天窗口
wx.SendMsg(msg) # 发送消息
wx.SendFiles(file) # 发送文件
print("发送结束!")