邮件发送
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
if file_name.endswith('.html'):
att = MIMEText(file_content, 'base64', 'utf-8')
msg_root.attach(att)
elif file_name.endswith('png'):
att = MIMEImage(file_content)
att.add_header('Content-ID', '<imagel>')
msg_root.attach(att)
else:
att = MIMEText(file_content, 'base64', 'utf-8')
msg_root.attach(att)
att['Content-Type'] = 'application/octet-stream'
att.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_name))
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 = ini._get('wechat_api', 'wx_url')
id_url = ini._get('wechat_api', 'id_url')
def send_file_to_wechat(file_path):
try:
file_content = {'file': open(file_path, 'rb')}
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)
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)