第六章:用Python实现自动发送邮件和发送钉钉消息
本文可以学习到以下内容:
- 使用requests库发送钉钉消息
- 使用email和smtplib库发送邮件
- 使用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 + "×tamp=" + 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
第六章:用Python实现自动发送邮件和发送钉钉消息的更多相关文章
- python selenium-7自动发送邮件
https://jingyan.baidu.com/article/647f0115b78f8d7f2148a8e8.html 1.发送HTML格式的邮件 import smtplib from em ...
- 第六章:Python基础の反射与常用模块解密
本课主题 反射 Mapping 介绍和操作实战 模块介绍和操作实战 random 模块 time 和 datetime 模块 logging 模块 sys 模块 os 模块 hashlib 模块 re ...
- python实现自动发送邮件
Python发送邮件成功的前提,应是先开启授权码.目前使用广泛的邮箱有:163邮箱.qq邮箱等. 163邮箱开启授权码的方法如下图: qq邮箱开启授权码的方法如下图: 接下来代码的实现: import ...
- 【TCP/IP详解 卷一:协议】第六章:DHCP 和自动配置
简介 为了使用 TCP/IP 协议族,每台主机or路由器都需要一定的配置信息: IP地址 子网掩码 广播地址 路由或转发表 DNS 协议配置方法: 手动 通过使用网络服务来获得 使用一些算法来自动确定 ...
- 第六章深入python的set和dict
1.collections中的abc MutableMapping是Mapping的子类 Mapping是Collection的子类 Collection是Sized,Iterable,Contain ...
- 第十六章:Python の Web开发基础(三) jQuery与Ajax
本課主題 jQuery 介绍 Ajax 介绍 jQuery 介绍 选择器 jQuery 的选择器分不同的种类,主要目的是用来查找目标的 HTML 标签,方便对目标标签进行操作,比如找到 <li& ...
- python如何自动发送邮件
#coding=utf-8 import smtplib from email.mime.text import MIMEText from email.mime.application import ...
- python接口自动化二(发送post请求)
前言 一个http请求包括三个部分,为别为请求行,请求报头,消息主体,类似以下这样: 请求行 请求报头 消息主体 HTTP协议规定post提交的数据必须放在消息主体中,但是协议并没有规定必须使用什么编 ...
- 【C#】新建服务自动发送邮件
---windows服务,---自动发送邮件 邮件发送code #region 发送邮件函数 public void SendMailUseZj() { System.Net.Mail.MailMes ...
- 简学Python第六章__class面向对象编程与异常处理
Python第六章__class面向对象编程与异常处理 欢迎加入Linux_Python学习群 群号:478616847 目录: 面向对象的程序设计 类和对象 封装 继承与派生 多态与多态性 特性p ...
随机推荐
- 花了半个小时基于 ChatGPT 搭建了一个微信机器人
相信大家最近被 ChatGPT 刷屏了,其实在差不多一个月前就火过一次,不会那会好像只在程序员的圈子里面火起来了,并没有被大众认知到,不知道最近是因为什么又火起来了,而且这次搞的人尽皆知. 想着这么火 ...
- 计算机网络基础08 Socket网络通信
部分内容来自:https://www.jianshu.com/p/066d99da7cbd 1 七层网络架构 在解释socket之前,先了解下七层网络架构 https://www.cnblogs.c ...
- The Missing Semester - 第一讲 学习笔记
The Missing Semester - 第一讲 学习笔记 第一讲 课程概览与 shell 课程视频地址: https://www.bilibili.com/video/BV1Eo4y1d7KZ/ ...
- PHP的25种框架
本篇文章给大家分享的内容是25种PHP框架 -有着一定的参考价值,有需要的朋友可以参考一下. 世界流行框架汇总 在项目开发中,一些架构和代码都是重复的,为了避免重复劳动,于是各种各样的框架诞生了. 在 ...
- LKWA靶机学习
LKWA靶机学习 目录 LKWA靶机学习 1 下载地址 2 Blind RCE 2.1 利用Burpsuite Collaborato模块来查看输出. 2.2 尝试利用dnslog进行回显 3 XSS ...
- Layui 表单元素考到页面样式不生效
表单元素必须要标记在表单里面(calss="layui-form") 例如: <div class="layui-form"> <input ...
- rem自动计算
写法一: //rem自动计算 (function (designWidth, maxWidth, viewWidth) { var doc = document, win = window, docE ...
- C# 元组类型和元组文本
从 C# 7.0 开始,可以使用元组类型和元组文本轻松实现此目的. 元组类型定义元 组元素的数据类型. 元组文本提供返回的元组的实际值. 在下面的示例中, (string, string, strin ...
- MySQL8.0 存储引擎(InnoDB )buffer pool的实现原理
数据库为了高效读取和存储物理数据,通常都会采用缓存的方式来弥补磁盘IO与CPU运算速度差.InnoDB 作为一个具有高可靠性和高性能的通用存储引擎也不例外,Buffer Pool就是其用来在内存中 ...
- Linux修改开机图形/etc/motd
修改 /etc/motd vim /etc/motd 植入图形 .--, .--, ( ( \.---./ ) ) '.__/o o\__.' {= ^ =} > - < / \ // \ ...