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 href="http://www.baidu.com">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   #飞书机器 人指南

posted @   風£飛  阅读(571)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-04-08 Linux网桥配置
点击右上角即可分享
微信分享提示