开启邮箱SMTP服务
以qq邮箱为例,其他邮箱均可仿照此方法开启。登录邮箱,点击设置:
点击账户:
开启POP3/SMTP(收/发件协议)服务:
之后使用手机短信进行验证,出现授权码:
发送明文邮件
首先需要第三方模块,安装yagmail:
pip install yagmail
导入模块,发送邮件模板:
yag = yagmail.SMTP(
user='⾃⼰的账号',
password='账号的授权码',
host='smtp.qq.com', # 邮局的 smtp 地址
port='端⼝号', # 邮局的 smtp 端⼝ 不加密25
smtp_ssl=False) # 使用25端口必须false
yag.send(to='收件箱账号',
subject='邮件主题',
contents='邮件内容')
import yagmail
# 开通SMTP服务的账号
email_user = 'xxx@qq.com'
# 客户端授权码
email_pwd = 'xxx'
# 从邮件服务提供商获取
email_host = 'smtp.qq.com'
# 邮件正文
email_content = "帝王只能是我迪亚波罗!"
yag = yagmail.SMTP(
user=email_user,
password=email_pwd,
host=email_host, # 邮局的 smtp 地址
port=25, # 邮局的 smtp 端⼝ 不加密25
smtp_ssl=False) # 使用25端口必须false
yag.send(to='xxx@qq.com', # 接受消息的账号
subject='未知',
contents=email_content)
查看接受方能否接收到:
成功接收!
群发加密邮件
import yagmail
# 开通SMTP服务的账号
email_user = 'xxx@qq.com'
# 客户端授权码
email_pwd = 'xxx'
# 从邮件服务提供商获取
email_host = 'smtp.qq.com'
# 邮件正文
email_content = "帝王只能是我迪亚波罗!"
yag = yagmail.SMTP(
user=email_user,
password=email_pwd,
host=email_host, # 邮局的 smtp 地址
port=465, # 邮局的 smtp 端⼝ 不加密25 加密端口465
smtp_ssl=True) # 使用25端口必须false
# 群发使用列表
email_users = ['xxx1@qq.com','xxx2@qq.com']
yag.send(to=email_users,
subject='未知',
contents=email_content,
# 增加附件写上文件路径
attachments='D:\Code\py\mailer\I.jpg'
)
文件内容:
查看是否接收到:
添加钉钉机器人
打开钉钉群聊,点击群设置:
点击自定义,添加:
发送钉钉消息
安装模块 requests:
pip3 install requests
import requests
#这里信息有自定义机器人的名字
sent_msg = "robot:帝王是我迪亚波罗!"
content = {
"msgtype": "text",
"text": {
"content": sent_msg
},
"at": {
# 发送给群里的所有人
"isAtAll": True
}
}
headers = {"Content_Type": "application/json;charset=utf-8"}
# 你自己生成的webhook
webhook = "https://oapi.dingtalk.com/robot/send?xxxxx"
r = requests.post(url=webhook, json=content, headers=headers)
print(r.content.decode())
钉钉:
控制台消息:
{"errcode":0,"errmsg":"ok"}
根据手机号发送:
import requests
sent_msg = "robot你好!"
content = {
"msgtype": "text",
"text": {
"content": sent_msg
},
"at": {
# 发送给群里的所有人
# "isAtAll": True
#手机号,可多选
"atMobiles":['xxxx','xxxxx']
}
}
headers = {"Content_Type": "application/json;charset=utf-8"}
# 你自己生成的webhook
webhook = "https://oapi.dingtalk.com/robot/send?xxxx"
r = requests.post(url=webhook, json=content, headers=headers)
print(r.content.decode())