Python数据分析实战【六】:用Python实现自动发送邮件和发送钉钉消息【文末源码地址】

目录

  • 发送邮件源码
  • 发送钉钉消息源码
  • 源码地址

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

  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'

{text}

'
# 实例化一个发送文本的邮箱对象 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 = '[email protected]' psw = 'xxxxxxxxxxxxxxxx' receivers = ["[email protected]", "[email protected]"] # 不发送附件方式 # 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,开发语言,自动发送邮箱,钉钉机器人,requests库)