本文可以学习到以下内容:

  1. 使用requests库发送钉钉消息
  2. 使用email和smtplib库发送邮件
  3. 使用163邮箱服务,自动发送邮件及附件

发送邮件源码

smtplib和email库都是python内置的标准库,不需要额外安装。

send_email函数是小凡封装的,参数解释如下:

text:邮件内容

server:发送邮件服务方,默认为163服务方

sender:发送人

receivers:接收人,多个接收人封装为列表

psw:从163邮箱获取的服务密码

attachment:附件,单个附件地址,或者多个附件地址列表

to:收件人名称

subject:邮件主题

源码如下:

import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication def send_email(text, server="smtp.163.com", sender=None, receivers=None, psw=None, attachment=None, to="收件人",subject="python自动发送邮件"):
"""
text:邮件内容
server:发送邮件服务方,默认为163服务方
sender:发送人
receivers:接收人,多个接收人封装为列表
psw:从163邮箱获取的服务密码
attachment:附件,单个附件地址,或者多个附件地址列表
to:收件人名称
subject:邮件主题
"""
# 实例化一个邮箱对象
smtp = smtplib.SMTP()
# 发送的文本内容
text = f'<p>{text}</p>'
# 实例化一个发送文本的邮箱对象
mime_text = MIMEText(_text=text, _subtype="html", _charset="utf-8")
# 发件人
mime_text["from"] = sender
# 收件人
mime_text["to"] = to
# 主题
# mime_text["subject"] = subject
# 创建一个多部分的邮箱对象
mime_multipart = MIMEMultipart()
# 邮箱主题
mime_multipart['Subject'] = subject
mime_multipart.attach(mime_text)
if attachment:
# 发送附件
if isinstance(attachment, str):
# 单个附件地址
with open(attachment, 'rb') as f:
mime_application = MIMEApplication(f.read())
mime_application.add_header('Content-Disposition', 'attachment', filename=attachment)
mime_multipart.attach(mime_application)
elif isinstance(attachment, list):
# 多个附件地址列表
for file in attachment:
with open(file, 'rb') as f:
mime_application = MIMEApplication(f.read())
mime_application.add_header('Content-Disposition', 'attachment', filename=file)
mime_multipart.attach(mime_application)
try:
# 连接并登录发送邮件的服务方
smtp.connect(server)
smtp.login(sender, password=psw)
# 发送邮件
smtp.sendmail(from_addr=sender, to_addrs=receivers, msg=mime_multipart.as_string())
print("发送邮件到 ", receivers, " 成功!")
except Exception as e:
print(str(e))
finally:
smtp.quit() if __name__ == '__main__':
text = "Python自动发送邮件"
sender = 'xxxxxxxxxxx@163.com'
psw = 'xxxxxxxxxxxxxxxx'
receivers = ["xxxxxxxxxx@qq.com", "xxxxxxxxxx@163.com"]
# 不发送附件方式
# send_email(text=text,sender=sender,psw=psw,receivers=receivers)
# 发送单个附件
# attachment = "./requirements.txt"
# send_email(text=text,sender=sender,psw=psw,receivers=receivers,attachment=attachment)
# 发送多个附件
# attachment = ["./requirements.txt","./sspython.ico"]
# send_email(text=text,sender=sender,psw=psw,receivers=receivers,attachment=attachment)

发送钉钉消息源码

参考钉钉开发文档,封装了dingding_robot函数。
参数解释如下:

title: 在消息显示的时候的简短信息

secret: 密钥

key_msg_list: 自定义的关键词列表

msg: 发送的信息

safe_set:安全设置,自定义关键词,加签

send_type: 发送内容的类型:text,markdown(md)

webhook: 申请的webhook

at_mobiles: 默认为None,指定@某人,传入列表

at_all: @所有人,传入True或者False

return: 发送是否成功标志

源码如下:

import requests
import time
import hmac
import hashlib
import base64
import urllib.parse def judge_msg(key_msg_list, msg):
"""
判断发送的消息中是否包含关键字
"""
for km in key_msg_list:
if km in msg:
return True
return False def make_sign(secret=None):
# 当安全设置选择加签方式时,制作秘钥
timestamp = str(round(time.time() * 1000))
if secret is None:
return None
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
return timestamp, sign def dingding_robot(msg=None, key_msg_list=None, safe_set=None, send_type=None, secret=None, webhook=None,
at_mobiles=None, at_all=False, title="钉钉机器人"):
"""
钉钉机器人
:param title: 在消息显示的时候的简短信息
:param secret: 密钥
:param key_msg_list: 自定义的关键词列表
:param msg: 发送的信息
:param safe_set:安全设置,自定义关键词,加签
:param send_type: 发送内容的类型:text,markdown(md)
:param webhook: 申请的webhook
:param at_mobiles: 默认为None,指定@某人,传入列表
:param at_all: @所有人,传入True或者False
:return: 发送是否成功标志
"""
if webhook is None:
print("webhook参数为必选项")
return None
if at_mobiles is None:
at_mobiles = []
if send_type not in ["text", "md", "markdown"]:
print("send_type必须为['text', 'md', 'markdown']其中一个")
return None
if safe_set in ['自定义关键词', '加签']:
header = {
"Content-Type": "application/json",
"Charset": "UTF-8"
}
send_content = {"at": {"atMobiles": at_mobiles, "isAtAll": at_all}}
if send_type == "text":
send_content["msgtype"] = "text"
send_content["text"] = {"content": msg}
elif send_type in ["md", "markdown"]:
send_content["msgtype"] = "markdown"
send_content["markdown"] = {"title": title, "text": msg}
if safe_set == "自定义关键词":
if not isinstance(key_msg_list, list) and not judge_msg(key_msg_list, msg):
print("key_msg_list传入自定义的关键词列表,msg中必须包含其中一个关键词")
return None
res = requests.post(url=webhook, json=send_content, headers=header)
return res.text
elif safe_set == "加签":
if secret:
timestamp, sign = make_sign(secret)
webhook = webhook + "&timestamp=" + timestamp + "&sign=" + sign
res = requests.post(url=webhook, json=send_content, headers=header)
return res.text
else:
print("secret为密钥,加签方式必须传入;")
return None
else:
print("safe_set参数为['自定义关键词', '加签']其中一个")
return None if __name__ == '__main__':
# 1、安全设置为自定义关键词
webhook = "从钉钉群中获取的webhook"
safe_set = "自定义关键词"
key_msg_list = ["自定义关键词1", "自定义关键词2", "自定义关键词3"]
msg = "发送的内容"
send_type = "text" # 或 md、或 markdown
at_mobiles = ["11111111111", "2222222222"] # 默认为 None
dingding_robot(webhook=webhook, safe_set=safe_set, key_msg_list=key_msg_list, msg=msg, send_type=send_type,
at_mobiles=at_mobiles)
# 2、安全设置为加签
# safe_set = "加签"
# secret = "xxxxxxxxxxxxxxxxxxxxxxx"
# dingding_robot(webhook=webhook, safe_set=safe_set, secret=secret, msg=msg, send_type=send_type,
# at_mobiles=at_mobiles)

源码地址

链接:https://pan.baidu.com/s/1Z0ecTuPmXSqgCnuvwn3rfg?pwd=g6b5
提取码:g6b5

最新文章

  1. IDE:IDEA Commit Changes Dialog local changes refresh
  2. Mac下Virtual Box Host-Only网络配置
  3. [Asp.net 5] DependencyInjection项目代码分析4-微软的实现(1)
  4. Html basic tag
  5. AutoCAD.NET二次开发:创建自定义菜单的两种方法比较
  6. Agile.Net 组件式开发平台 - 平台系统介绍
  7. Bzoj 1616: [Usaco2008 Mar]Cow Travelling游荡的奶牛 动态规划
  8. cmd 进入不同的驱动盘及上下级目录
  9. 跨浏览器读取XML
  10. PHP 函数的引用传递
  11. #include &lt;boost/shared_ptr.hpp&gt;
  12. Mysql 子查询
  13. vuex入门文档
  14. base64变形注入与联合查询注入的爱情故事
  15. C++11学习笔记之三lamda表达式,std::function, std::bind
  16. CVE-2015-1642 POC
  17. Jenkins系列-Jenkins介绍与部署
  18. tpot蜜罐平台搭建
  19. 【转】ANDROID自定义视图——onLayout源码 流程 思路详解
  20. ActiveMQ(4) ActiveMQ JDBC 持久化 Mysql 数据库

热门文章

  1. JAVA虚拟机02---JAVA虚拟机运行时数据区域简介
  2. 又花了半个小时将 ChatGPT 接入了钉钉机器人
  3. 安卓逆向4.xpsoed hook构造方法
  4. K8s 网络新手教程(Kubernetes Networking Guide for Beginners)
  5. CF1625D.Binary Spiders
  6. php使用PDO获取结果集的方法
  7. 关于 Knex update 语句报错:Undefined binding(s) detected when compiling UPDATE
  8. 空间数据库中ST_开头的来由
  9. 遥感影像和DEM数据获取处理、GeoServer切片发布并使用Cesium加载
  10. pytorch学习笔记三之神经网络