python-发送邮件,调用企业微信机器人发送消息

邮件发送

# _*_coding: UTF-8 _*_
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os
from email.mime.image import MIMEImage


# 发送邮件

def send_report(file_name):
    # 获取配置文件中收发件成员
    # 发送邮箱的服务器、账号、密码
    server = 'smtp.163.com'
    passwd = '授权码'
    # 发送邮箱
    sender = '111@163.com'
    # 收件人
    receiver = '222@qq.com'
    # 邮件的标题、内容
    subject = '邮件的标题' + time.strftime('%Y-%m-%d %H:%M:%S')
	
	# 非二进制内容
    if file_name.endswith('.log'):
        with open(file_name, 'r', encoding='utf-8') as fp:
            file_content = fp.read()
    else:
    # 二进制形式读取内容
        with open(file_name, 'rb') as fp:
            file_content = fp.read()
    # 构造邮件(主题、正文+附加)
    msg_root = MIMEMultipart('related')
    msg_root['Subject'] = subject

    # body = MIMEText(file_content, 'html', 'utf-8')
    # att = MIMEText(file_content, 'base64', 'utf-8')
    if file_name.endswith('.html'):
        # 邮件正文
        # body = MIMEText(file_content, _subtype='html', _charset='utf-8')
        # 邮件附件
        att = MIMEText(file_content, 'base64', 'utf-8')
        # msg_root.attach(body)
        msg_root.attach(att)
    elif file_name.endswith('png'):
        # att = MIMEBase(file_content, 'base64', 'utf-8')
        att = MIMEImage(file_content)
        # att = (file_content,image,)
        att.add_header('Content-ID', '<imagel>')
        msg_root.attach(att)
    else:
        # body = MIMEText(file_content, format, _charset="utf-8")
        att = MIMEText(file_content, 'base64', 'utf-8')
        # body["Accept-Language"] = "zh-CN"
        # body["Accept-Charset"] = "utf-8"
        # msg_root.attach(body)
        msg_root.attach(att)
    att['Content-Type'] = 'application/octet-stream'
    att.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_name))

    # SSL协议端口号要使用465
    smtp = smtplib.SMTP_SSL(server, 465)
    # 定义收发件角色
    msg_root['from'] = sender
    msg_root['to'] = receiver
    # 向用户标识用户身份
    smtp.helo(server)
    # 服务器返回结果确认
    smtp.ehlo(server)
    # 连接邮箱、发送邮件
    smtp = smtplib.SMTP()
    smtp.connect(server)
    # 登陆发件者邮箱
    smtp.login(sender, passwd)
    # 发送邮件
    try:
        smtp.sendmail(sender, receiver.split(','), msg_root.as_string())
    except Exception as e:
        print(e)
        raise Exception(f"发送邮件发生异常: {e}")
    finally:
        smtp.quit()


if __name__ == '__main__':
    # 发送邮件
    send_report(log_file)

企业微信机器人发送消息


import requests

# 企业微信机器人的wx_url和id_url,在机器人设置里获取
wx_url = ini._get('wechat_api', 'wx_url')
id_url = ini._get('wechat_api', 'id_url')


def send_file_to_wechat(file_path):
    try:
        # 1. 读取文件内容
        file_content = {'file': open(file_path, 'rb')}
        # 请求id_url(将文件上传微信临时平台),返回media_id
        temp_response = requests.post(url=id_url, files=file_content)
        json_res = temp_response.json()
        media_id = json_res['media_id']

        data = {"msgtype": "file",
                "file": {"media_id": media_id}
                }
        response = requests.post(url=wx_url, json=data)
        # 5. 处理响应
        if response.status_code == 200 and response.json()['errcode'] == 0:
            print("企业微信信息发送成功")
        else:
            print(f'企业微信信息发送失败,响应内容如下:{response.text}')
    except Exception as e:
        raise Exception(f"企业微信信息发送异常:{e}")


if __name__ == '__main__':
    # 发送企业微信
    send_file_to_wechat(log_file)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值