當前位置:
首頁 >
Python发送飞书消息
發布時間:2023/10/11
85
如意码农
生活随笔
收集整理的這篇文章主要介紹了
Python发送飞书消息
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#!/usr/bin/python3.8
# -*- coding:UTF-8 -*- import os, sys
sys.path.append(os.path.dirname(os.path.abspath(__file__))) import time, json
import requests
from function.conndb import condb
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.header import Header
import base64 class SendMail(object):
def __init__(self, username, passwd, email_host, recv, title, content, file=None, imagefile=None, ssl=False,
port=25, ssl_port=465):
'''
:param username: 用戶名
:param passwd: 密碼
:param email_host: smtp服務器地址
:param recv: 收件人,多個要傳list ['a@qq.com','b@qq.com]
:param title: 郵件標題
:param content: 郵件正文
:param file: 附件路徑,如果不在當前目錄下,要寫絕對路徑,默認沒有附件
:param imagefile: 圖片路徑,如果不在當前目錄下,要寫絕對路徑,默認沒有圖片
:param ssl: 是否安全鏈接,默認為普通
:param port: 非安全鏈接端口,默認為25
:param ssl_port: 安全鏈接端口,默認為465
'''
self.username = username # 用戶名
self.passwd = passwd # 密碼
self.recv = recv # 收件人,多個要傳list ['a@qq.com','b@qq.com]
self.title = title # 郵件標題
self.content = content # 郵件正文
self.file = file # 附件路徑,如果不在當前目錄下,要寫絕對路徑
self.imagefile = imagefile # 圖片路徑,如果不在當前目錄下,要寫絕對路徑
self.email_host = email_host # smtp服務器地址
self.port = port # 普通端口
self.ssl = ssl # 是否安全鏈接
self.ssl_port = ssl_port # 安全鏈接端口 def send_mail(self):
# msg = MIMEMultipart()
msg = MIMEMultipart('mixed')
# 發送內容的對象
if self.file: # 處理附件的
file_name = os.path.split(self.file)[-1] # 只取文件名,不取路徑
try:
f = open(self.file, 'rb').read()
except Exception as e:
raise Exception('附件打不開!!!!')
else:
att = MIMEText(f, "base64", "utf-8")
att["Content-Type"] = 'application/octet-stream'
# base64.b64encode(file_name.encode()).decode()
new_file_name = '=?utf-8?b?' + base64.b64encode(file_name.encode()).decode() + '?='
# 這里是處理文件名為中文名的,必須這么寫
att["Content-Disposition"] = 'attachment; filename="%s"' % (new_file_name)
msg.attach(att)
if self.imagefile:
try:
sendimagefile = open(self.imagefile, 'rb').read()
except Exception as e:
raise Exception('圖片無法打開!!!!')
else:
image = MIMEImage(sendimagefile)
image.add_header('Content-ID', '<image1>')
msg.attach(image)
text_html = MIMEText(self.content, 'html', 'utf-8')
msg.attach(text_html)
# msg.attach(MIMEText(self.content)) # 郵件正文的內容
msg['Subject'] = self.title # 郵件主題
msg['From'] = self.username # 發送者賬號
msg['To'] = ','.join(self.recv) # 接收者賬號列表
if self.ssl:
self.smtp = smtplib.SMTP_SSL(self.email_host, port=self.ssl_port)
else:
self.smtp = smtplib.SMTP(self.email_host, port=self.port)
# 發送郵件服務器的對象
self.smtp.login(self.username, self.passwd)
try:
self.smtp.sendmail(self.username, self.recv, msg.as_string())
pass
except Exception as e:
print('出錯了。。', e)
else:
print('發送成功!{}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
self.smtp.quit() def calculate_time(last_time):
"""
計算兩個時間相差天數
:param lastdate: 類型為日期類型
:return: 返回與當前時間相差的天數
"""
timestamp_day1 = time.mktime(time.strptime(last_time, "%Y-%m-%d"))
timestamp_day2 = time.mktime(time.strptime(time.strftime("%Y-%m-%d", time.localtime()), "%Y-%m-%d"))
result = (timestamp_day1 - timestamp_day2) // 60 // 60 // 24
return int(result) def report(username, book, givetime, datenumber):
"""
發送消息到飛書機器人
:param username:
:param book:
:param givetime:
:param datenumber:
:return:
"""
data = {"msg_type": "post", "content": {"post": {
"zh_cn": {"title": "書籍借閱通知", "content": [
[{"tag": "text", "text": "姓名:%s" % (username)}],
[{"tag": "text", "text": "借閱書籍:%s" % (book)}],
[{"tag": "text", "text": "歸還時間:%s" % (givetime)}],
[{"tag": "text", "text": "距離歸還時間還有(%s)天" % (datenumber)}]
]}}}}
headers = {"Content-Type": "application/json"}
requests.post(url='https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxx',
headers=headers, data=json.dumps(data)) if __name__ == '__main__':
re, reall = condb('SELECT book.name,gtime,chinesename FROM book INNER JOIN person ON book.pid = person.id;')
res, resall = condb('SELECT id,chinesename,mail,birthday FROM person;') for dt in reall:
givetime = dt.get('gtime').strftime("%Y-%m-%d")
day_diff = calculate_time(givetime)
if 0 <= day_diff < 3:
report(dt.get('chinesename'), dt.get('name'), givetime, day_diff) for bd in resall:
date1 = bd.get('birthday').strftime("%m-%d")
date2 = time.strftime("%m-%d", time.localtime())
if date1 == date2:
m = SendMail(
username='xxxxxx@qq.com',
passwd='xxxxxx',
email_host='smtp.exmail.qq.com',
recv=[bd.get('mail')],
title='祝您生日快樂',
content="""
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a >link</a> you wanted.<br>
</p>
<img src="cid:image1">
</body>
</html>
""",
imagefile=r'test.png',
ssl=True,
)
m.send_mail()
# print('生日快樂', bd.get('chinesename'))
https://open.feishu.cn/document/ukTMukTMukTM/ucTM5YjL3ETO24yNxkjN #飛書機器 人指南
總結
以上是生活随笔為你收集整理的Python发送飞书消息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux 字符集与编码格式相关
- 下一篇: 使用Echarts 动态更新散点图