Python推送消息

一、Python直接给微信推送消息

这里使用了一个第三方工具pushplus

单人推送

实现步骤:

1、用微信注册一个此网站的账号
2、将token复制出来,记录到小本本上。

![图片](https://img-blog.csdnimg.cn/c0bce77e53d746a6966fb90e5deca12c.png

代码展示

import requests

def send_wechat(msg):
    token = '你的那个'#前边复制到那个token
    title = 'title1'
    content = msg
    template = 'html'
    url = f"https://www.pushplus.plus/send?token={
      
      token}&title={
      
      title}&content={
      
      content}&template={
      
      template}"
    print(url)
    r = requests.get(url=url)
    print(r.text)

if __name__ == '__main__':
    msg = 'Life is short I use python'
    send_wechat(msg)

在手机上看一下结果

图片

局限性:这个只能给自己推送,别人推送不了。那怎么给别人推送呢?

一对多推送

实现步骤

1、在一对多推送的tab页面里,新建群组,并记录下群组编码。
在这里插入图片描述
在这里插入图片描述

2、点击生成二维码,将二维码发给要接受消息的人。让他们用微信扫码。

图片

3、扫码后,看看订阅人,扫码之后的人,会显示在这里。给这个群组发送的消息,这里的人都会接收到。

图片

4、代码

import requests

def send_wechat(msg):
    token = ' 你的那个' #前边复制到那个token
    title = 'test notice title'
    content = msg
    template = 'html'
    topic = '1'
    url = f"http://www.pushplus.plus/send?token={
      
      token}&title={
      
      title}&content={
      
      content}&template={
      
      template}&topic={
      
      topic}"
    print(url)
    r = requests.get(url=url)
    print(r.text)

if __name__ == '__main__':
    msg = 'this is a one to more lizi'
    send_wechat(msg)

效果展示

图片

至此微信推送到这里就完成啦!

二、Python直接给QQ邮箱推送消息

代码前准备:

获取smtp授权码:

1.进入设置

2.进入账户

3.开启smtp服务并且获取授权码(可以生成多个授权码,授权码就是后面代码的key)
在这里插入图片描述

# coding=utf-8
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication

def mailing(content,imageFile,excelFile):
    # 配置邮箱信息
    sender = '@qq.com'  # 发件人的地址
    password = 'u224####hcg'  # 此处是我们刚刚在邮箱中获取的授权码
    # 收件人信息
    # receivers = 'li###[email protected]'#,"25##[email protected]"  # 邮件接受方邮箱地址,可以配置多个,实现群发,注意这里要是字符串
    mail_receivers = ['##[email protected]', "12##[email protected]"]
    # 邮件内容设置
    # content = MIMEText(
    #     "<html><h2>努力赚钱才是正经事,穷人的精力更多是在思考如何生活,富人才有精力享受生活。</h2>"
    #     "<br>"
    #     "<a href='https://blog.csdn.net/weixin_52051554?type=blog'>我的CSDN</a></html>"
    #     "<br>"
    #     "<font color='red' size='10'>这是红色字体</font>",
    #     _subtype="html", _charset="utf-8")
    msg = MIMEMultipart('related')
    msg.attach(content)

    # 简单的说明下HTML语法的意思
    # h2:字体标题h2
    # br:换行
    # a href:超链接
    # font:设置字体大小和颜色等
    # message = MIMEText('你好呀,这是来自QQ邮箱的信息--from python发送~!', 'plain', 'utf-8')
    # message = msg = MIMEText(
    #     "<html><h2>努力赚钱才是正经事,穷人的精力更多是在思考如何生活,富人才有精力享受生活。比如,她晚上邀你去她家做客,没钱的人或许会因为心疼打车钱而止步,有钱的人只会因为正在另一位姑娘家做客而拒绝。</h2>"
    #     "<br>"
    #     "<a href='https://blog.csdn.net/zcm545186061'>我的CSDN</a></html>"
    #     "<br>"
    #     "<font color='red' size='10'>这是红色字体</font>",
    #     _subtype="html", _charset="utf-8")

    # 添加图片附件
    #imageFile = r"2111.jpg"
    imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
    imageApart.add_header('Content-Disposition', 'attachment', filename=imageFile)
    msg.attach(imageApart)

    # 添加Excel附件
    # excelFile = r'sample1.xlsx'
    excelApart = MIMEApplication(open(excelFile, 'rb').read())
    excelApart.add_header('Content-Disposition', 'attachment', filename=excelFile)
    msg.attach(excelApart)

    # 邮件标题设置
    msg['Subject'] = 'python发送附件测试-图片、Excel'

    # 发件人信息
    msg['From'] = sender

    # 收件人信息
    # msg['To'] = receivers

    # 通过授权码,登录邮箱,并发送邮件
    try:
        server = smtplib.SMTP('smtp.qq.com')  # 配置QQ邮箱的smtp服务器地址
        server.login(sender, password)  # msg['To'].split(',')#->mail_receivers
        server.sendmail(msg['From'], mail_receivers, msg.as_string())
        print('发送成功')
        server.quit()

    except smtplib.SMTPException as e:
        print('error', e)


if __name__ == '__main__':
    excelFile = r'sample1.xlsx'
    imageFile = r"2111.jpg"
    content = MIMEText(
        "<html><h2>努力赚钱才是正经事,穷人的精力更多是在思考如何生活,富人才有精力享受生活。比如,她晚上邀你去她家做客,没钱的人或许会因为心疼打车钱而止步,有钱的人只会因为正在另一位姑娘家做客而拒绝。</h2>"
        "<br>"
        "<a href='https://blog.csdn.net/weixin_52051554?type=blog'>我的CSDN</a></html>"
        "<br>"
        "<font color='red' size='10'>这是红色字体</font>",
        _subtype="html", _charset="utf-8")
    mailing(content,imageFile,excelFile)


三、163邮箱

准备部分与QQ邮箱类似

import smtplib
import email
# 负责构造文本
from email.mime.text import MIMEText
# 负责构造图片
from email.mime.image import MIMEImage
# 负责将多个对象集合起来
from email.mime.multipart import MIMEMultipart
from email.header import Header

# SMTP服务器,这里使用163邮箱
mail_host = "smtp.163.com"
# 发件人邮箱
mail_sender = "liu####[email protected]"
# 邮箱授权码,注意这里不是邮箱密码,如何获取邮箱授权码,请看本文最后教程
mail_license = "OCRZ####XRNVXM"
# 收件人邮箱,可以为多个收件人
mail_receivers = ["269###[email protected]","25####[email protected]"]

mm = MIMEMultipart('related')

# 邮件主题
subject_content = """Python邮件测试"""
# 设置发送者,注意严格遵守格式,里面邮箱为发件人邮箱
mm["From"] = "sender_name<[email protected]>"
# 设置接受者,注意严格遵守格式,里面邮箱为接受者邮箱
mm["To"] = "receiver_1_name<[email protected]>,receiver_2_name<[email protected]>"
# 设置邮件主题
mm["Subject"] = Header(subject_content,'utf-8')

# 邮件正文内容
body_content = """你好,今天开心吗?"""
# 构造文本,参数1:正文内容,参数2:文本格式,参数3:编码方式
message_text = MIMEText(body_content,"plain","utf-8")
# 向MIMEMultipart对象中添加文本对象
mm.attach(message_text)

# 二进制读取图片
image_data = open('2111.jpg','rb')
# 设置读取获取的二进制数据
message_image = MIMEImage(image_data.read())
# 关闭刚才打开的文件
image_data.close()
# 添加图片文件到邮件信息当中去
mm.attach(message_image)

# 构造附件
atta = MIMEText(open('sample1.xlsx', 'rb').read(), 'base64', 'utf-8')
# 设置附件信息
atta["Content-Disposition"] = 'attachment; filename="sample1.xlsx"'
# 添加附件到邮件信息当中去
mm.attach(atta)

# 创建SMTP对象
stp = smtplib.SMTP()
# 设置发件人邮箱的域名和端口,端口地址为25
stp.connect(mail_host, 25)
# set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息
stp.set_debuglevel(1)
# 登录邮箱,传递参数1:邮箱地址,参数2:邮箱授权码
stp.login(mail_sender,mail_license)
# 发送邮件,传递参数1:发件人邮箱地址,参数2:收件人邮箱地址,参数3:把邮件内容格式改为str
stp.sendmail(mail_sender, mail_receivers, mm.as_string())
print("邮件发送成功")
# 关闭SMTP对象
stp.quit()

四、python发短信

先登录下方网址进行注册

# coding=utf-8
import urllib
import urllib.request


def md5(str):
    import hashlib
    m = hashlib.md5()
    m.update(str.encode("utf8"))
    return m.hexdigest()


def warning():
    statusStr = {
    
    
        '0': '短信发送成功',
        '-1': '参数不全',
        '-2': '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间',
        '30': '密码错误',
        '40': '账号不存在',
        '41': '余额不足',
        '42': '账户已过期',
        '43': 'IP地址限制',
        '50': '内容含有敏感词'
    }
    smsapi = "http://api.smsbao.com/"
    # 短信平台账号
    user = '18####648'
    # 短信平台密码
    password = md5('c4cb5b1#####07c####45')
    # 要发送的短信内容
    content = "【紧急警报】\n原因:检测到未知人员\n地点:2111"
    # 要发送短信的手机号码
    phone = '15####014'

    data = urllib.parse.urlencode({
    
    'u': user, 'p': password, 'm': phone, 'c': content})
    send_url = smsapi + 'sms?' + data
    response = urllib.request.urlopen(send_url)
    the_page = response.read().decode('utf-8')
    print(statusStr[the_page])


if __name__ == '__main__':
    warning()

猜你喜欢

转载自blog.csdn.net/weixin_52051554/article/details/130301479
今日推荐