Python处理邮件和机器人的实用姿势

{"type":"doc","content":[{"type":"heading","attrs":{"align":null,"level":1}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 没有看不到的消息,只有不想回的人。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"电子邮件是最古老的互联网应用之一。在移动互联网和即时通讯没爆发前,邮件是人们沟通的主要形式。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"和HTTP网页服务一样,电子邮件也有自己的协议:"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"SMTP"}]},{"type":"text","text":":用来发邮件的协议。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"POP3"}]},{"type":"text","text":":用来收邮件的协议,数据单向从邮箱传递给客户端。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"IMAP"}]},{"type":"text","text":":是"},{"type":"codeinline","content":[{"type":"text","text":"POP3"}]},{"type":"text","text":"的扩展,可以浏览摘要后再选择下载邮件,也可以从本地同步数据给邮箱。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Python提供了4个标准模块处理邮件:"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"smtplib"}]},{"type":"text","text":",用于发邮件。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"poplib"}]},{"type":"text","text":",用"},{"type":"codeinline","content":[{"type":"text","text":"POP3"}]},{"type":"text","text":"协议收邮件。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"imaplib"}]},{"type":"text","text":",用"},{"type":"codeinline","content":[{"type":"text","text":"IMAP"}]},{"type":"text","text":"协议同步客户端和邮箱数据。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"email"}]},{"type":"text","text":",用于解析邮件内容结构。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"20年前,只要你能连到互联网,就能提供邮箱服务。那时候的互联网,除了门户网站,就是电子邮件。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"随着准入门槛的提高,目前邮箱服务主要由电信运营商和几个互联网巨头提供,以Web版和App客户端为主,一般都需要独立授权码才能开启三方客户端访问其"},{"type":"codeinline","content":[{"type":"text","text":"SMTP/IMAP/POP3"}]},{"type":"text","text":"接口。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/8d/8d7d4e984a3404c0028f8bcbb3371bdd.png","alt":"image-20200820001117135","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/d5/d53d7eaf8237891f7c3198a508b9d245.png","alt":"image-20200820093416547","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"邮件主要的2个用途:正式沟通、自动通知。"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" "},{"type":"text","marks":[{"type":"strong"}],"text":"“正式沟通”"},{"type":"text","text":"指较为正式的事项确认,工作中较常见。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" "},{"type":"text","marks":[{"type":"strong"}],"text":"“自动通知”"},{"type":"text","text":"指主动发送或者当条件出发时自动发送邮件。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"“自动通知”的应用范围较广,如订阅频道后定期推送内容,代码构建失败后通知成员,每日收集情报后汇总发送给有关人员等等。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"随着互联网办公软件成熟,群组功能在企业内应用也更加广泛,企业微信和钉钉是国内2个最主流的企业办公服务软件。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"它们都提供了机器人功能,可以自动通知消息到所在群组成员,比邮件及时,也更灵活。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/29/29113960367efa486fc3f9c43b7cf192.png","alt":"image-20200821095423135","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"所以我们可以把这类应用归为自动通知场景:"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"自动发送邮件:如定时周报或条件触发后自动邮件通知。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"归档整理邮件:自动下载邮件,提取内容保存,如附件。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"机器人通知:钉钉和企业微信群内自动通知相关成员。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"发送邮件"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"用Python发邮件主要分3步:"}]},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"构造邮件内容"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"账号登陆授权"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"发送邮件消息"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"其中有几个注意点:"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"登陆密码是授权码,而非邮箱Web版客户端的登陆密码。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"有些服务商会选用自定义端口并要求用SSL加密后发邮件。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"不同服务商在协议实现支持上可能会有不同,有些服务商会禁止通过协议访问邮箱数据。此外用非官方客户端访问时,会出现'system busy'等提示,估计资源分配不如官方版本。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"真正发送者和目标在"},{"type":"codeinline","content":[{"type":"text","text":"sendmail()"}]},{"type":"text","text":"方法中指定,邮件中的"},{"type":"codeinline","content":[{"type":"text","text":"From"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":"To"}]},{"type":"text","text":"只是内容一部分。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"尤其是最后一点,早先成了不少电子邮件欺诈者的帮凶,理论上的“发件人”你可以写任何名字。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"比如下面标示的邮箱地址都是“假的”。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/83/8371781a1ce645cd8ec0516db2136345.png","alt":"image-20200820004725145","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"目前一些服务商会对邮件内容做敏感信息过滤。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"发送纯文本邮件"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"python"},"content":[{"type":"text","text":"# 纯文本邮件\nimport smtplib\nfrom email.mime.text import MIMEText\n# 构造邮件\nmsg = MIMEText('Hello Python1024!', 'plain', 'utf-8')\nmsg['From'] = '程一初 '\nmsg['To'] = '程一初1 , 程一初2 '\nmsg['Subject'] = '来自Python1024'\nfrom_addr = '[email protected]'\n# 密码是授权码\npassword = ''\nto_addr = '[email protected]'\nsmtp_server = 'smtp.qq.com'\n# QQ邮箱的SMTP服务需SSL加密,端口为465\nserver = smtplib.SMTP_SSL(smtp_server)\n# 显示发送过程\nserver.set_debuglevel(1)\n# 登陆验证\nserver.login(from_addr, password)\n# 发送邮件\nserver.sendmail(from_addr, [to_addr], msg.as_string())\n# 退出\nserver.quit()"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"发送HTML邮件"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"python"},"content":[{"type":"text","text":"import smtplib\nfrom email.mime.text import MIMEText\n# 构造邮件\nmsg = MIMEText('

Python1024

' +\n '

程一初 发送。

', 'html', 'utf-8')\nmsg['From'] = '程一初 '\nmsg['To'] = '程一初1 , 程一初2 '\nmsg['Subject'] = '来自Python1024'\nfrom_addr = '[email protected]'\n# 密码是授权码\npassword = ''\nto_addr = '[email protected]'\nsmtp_server = 'smtp.qq.com'\nserver = smtplib.SMTP_SSL(smtp_server, 465)\nserver.login(from_addr, password)\nserver.sendmail(from_addr, [to_addr], msg.as_string())\nserver.quit()"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"发送带附件邮件"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"python"},"content":[{"type":"text","text":"import pathlib\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.image import MIMEImage\nfrom email.mime.application import MIMEApplication\npath = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/009email')\nfile_path = path.joinpath('avatar.jpg')\nzip_path = path.joinpath('avatar.jpg.zip')\n# 构造邮件\nmsg = MIMEMultipart()\nmsg['From'] = '程一初 '\nmsg['To'] = '程一初1 , 程一初2 '\nmsg['Subject'] = '来自Python1024'\nfrom_addr = '[email protected]'\nmsg.attach(MIMEText('请查收附件', 'html', 'utf-8'))\n# 图像文件在邮箱Web客户端中可以预览\nwith open(file_path, 'rb') as f:\n mime = MIMEImage(f.read())\n mime.add_header('Content-Disposition', 'attachment',\n filename=file_path.name)\n mime.add_header('Content-ID', '')\n msg.attach(mime)\n# 其他应用文件\nwith open(zip_path, 'rb') as f:\n mime = MIMEApplication(f.read())\n mime.add_header('Content-Disposition', 'attachment',\n filename=zip_path.name)\n msg.attach(mime)\npassword = ''\nto_addr = '[email protected]'\nsmtp_server = 'smtp.qq.com'\nserver = smtplib.SMTP_SSL(smtp_server, 465)\nserver.login(from_addr, password)\nserver.sendmail(from_addr, [to_addr], msg.as_string())\nserver.quit()"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"收邮件"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Python收邮件可以选择使用"},{"type":"codeinline","content":[{"type":"text","text":"POP3"}]},{"type":"text","text":"或"},{"type":"codeinline","content":[{"type":"text","text":"IMAP"}]},{"type":"text","text":"两种协议。"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"poplib"}]},{"type":"text","text":":用"},{"type":"codeinline","content":[{"type":"text","text":"POP3"}]},{"type":"text","text":"协议收取MIME内容。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"smtplib"}]},{"type":"text","text":":用"},{"type":"codeinline","content":[{"type":"text","text":"IMAP"}]},{"type":"text","text":"获取邮箱内容,也可以同步数据给邮箱,数据可以双向传递。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"从邮箱收到数据后,可以用"},{"type":"codeinline","content":[{"type":"text","text":"email"}]},{"type":"text","text":"模块按邮件标准格式解析。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"用"},{"type":"codeinline","content":[{"type":"text","text":"POP3"}]},{"type":"text","text":"自动下载邮件"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"python"},"content":[{"type":"text","text":"import pathlib\nimport poplib\nfrom email.parser import Parser\nfrom email.header import Header, decode_header\npath = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/009email')\nout_path = path.joinpath('009email_pop3')\n\ndef download_msg(msg, idx, path=out_path):\n \"\"\"解析邮件并保存到文件\"\"\"\n for part in msg.walk():\n # 遍历邮件内容\n if not part.is_multipart():\n # 有文件名即为附件\n filename = part.get_filename()\n # 获取内容并解码\n content = part.get_payload(decode=True)\n if filename:\n # 获取信息头中文件名\n h = decode_header(Header(filename))\n filename = str(h[0][0], encoding='utf-8')\n file_path = path.joinpath(f'mail_{idx}_attach_{filename}')\n else:\n file_path = path.joinpath(f'mail_{idx}_text')\n with open(path.joinpath(file_path), 'wb') as f:\n f.write(content)\n\nuser = '[email protected]'\npassword = ''\npop3_svr = 'pop.qq.com'\nsvr = poplib.POP3_SSL(pop3_svr)\nsvr.set_debuglevel(1)\nprint(svr.getwelcome().decode('utf-8'))\n# 认证登陆\nsvr.user(user)\nsvr.pass_(password)\n# 查看邮箱内邮件数、占用空间\nprint('邮件 {} 封, 占用 {} 字节。'.format(*svr.stat()))\n# 邮件列表\nresp, mails, octets = svr.list()\nprint(mails)\n# 获取最新邮件, 注意索引从1开始\nindex = len(mails)\nresp, lines, octets = svr.retr(index)\n# 获取的邮件内容按行合并\nmsg_content = b'\\r\\n'.join(lines).decode('utf-8')\n# 获取MIME对象\nmsg = Parser().parsestr(msg_content)\n# 下载邮件内容\ndownload_msg(msg, index)\nsvr.quit()"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"用"},{"type":"codeinline","content":[{"type":"text","text":"IMAP"}]},{"type":"text","text":"自动下载邮件"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"python"},"content":[{"type":"text","text":"import re\nimport pathlib\nimport imaplib\nimport email\nfrom email.parser import BytesFeedParser\nfrom email.header import Header, decode_header, make_header\n\npath = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/009email')\nout_path = path.joinpath('009email_imap')\n\ndef download_msg(msg, idx, path=out_path):\n # \n pass\n\nuser = '[email protected]'\npassword = ''\nimap_svr = 'imap.qq.com'\nimaplib.Debug = 4\nsvr = imaplib.IMAP4_SSL(imap_svr)\nsvr.login(user, password)\nprint(svr.welcome)\n# 列出所有邮箱\nrcode, mbox_list = svr.list()\n# 用正则表达式解析信息\nlist_pattern = re.compile(r'.(?P.*?). \"(?P.*)\" (?P.*)')\nfor mbox in mbox_list:\n flags, delimiter, mbox_name = list_pattern.match(mbox.decode('utf-8')).groups()\n print(mbox_name.strip())\n# 检查某个邮箱状态,如邮件数、未读邮件等\nrcode, res = svr.status('INBOX','(MESSAGES RECENT UNSEEN)',)\nprint(res)\n# 选择一个邮箱\nrcode, res = svr.select('INBOX', readonly=True)\nprint(f'共有 {int(res[0])} 封邮件')\n# 查询未读邮件,返回邮件ID\nrcode, msg_ids = svr.search('(UNSEEN)')\nprint(msg_ids)\n# QQMail的IMAP不支持按主题搜索,搜索功能有限\nrcode, msg_ids = svr.search('(SUBJECT \"python1024\")',)\nprint(rcode, msg_ids)\nfor m in msg_ids[0].split():\n # 根据邮件ID获取邮件,按RFC822格式\n rcode, msg_data = svr.fetch(m, '(RFC822)')\n for part in msg_data:\n if isinstance(part, tuple):\n msg = email.message_from_bytes(part[1])\n download_msg(msg, str(m, encoding='utf-8'), out_path)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"用"},{"type":"codeinline","content":[{"type":"text","text":"IMAP"}]},{"type":"text","text":"协议同步信息到邮箱"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"python"},"content":[{"type":"text","text":"import time\nimport imaplib\nfrom email.message import Message\n\nuser = '[email protected]'\npassword = ''\nimap_svr = 'imap.qq.com'\nimaplib.Debug = 4\nsvr = imaplib.IMAP4_SSL(imap_svr)\nsvr.login(user, password)\n# 创建一个邮箱\nrcode, res = svr.create('python1024')\nprint(rcode, res)\n# 构造一条邮件信息\nmsg = Message()\nmsg.set_unixfrom('pymotw')\nmsg['Subject'] = 'Python1024上传主题'\nmsg['From'] = '[email protected]'\nmsg['To'] = '[email protected]'\nmsg.set_payload('这是Python1024上传的信息')\n# 上传信息\nsvr.append('python1024', '',\n imaplib.Time2Internaldate(time.time()),\n str(msg).encode('utf-8'))\nrcode, res = svr.select('python1024')\nprint(f'有{res[0]}封邮件。')\nrcode, res = svr.search('ALL')\nmsg_id = res[0].split()[-1]\n# 设置新信息未读状态\nsvr.store(msg_id, '-FLAGS', '(\\Seen)')\nrcode, res = svr.fetch(msg_id, '(FLAGS)')\nprint(res)\n# 可以把消息复制到其他邮箱\nsvr.copy(msg_id, 'INBOX')"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"机器人应用"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这里所谓的机器人,是指钉钉、企业微信中参与聊天的机器人账号。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"其本质是一个"},{"type":"codeinline","content":[{"type":"text","text":"restful"}]},{"type":"text","text":"接口的账号,通过接口控制账号行为。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"目前这类机器人主要应用场景有:"}]},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"快速传达信息到社群内,如技术运维、运营分析、情报获取等信息。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"打造自动社群体验流程,如自助客服、新业务体验等。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在钉钉和企业微信中,一般由管理员创建机器人:"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"钉钉群和企业微信内部群支持机器人主动发送信息。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"企业微信外部群机器人只能被动回应关键词,不能主动发信息。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下面主要介绍钉钉和企业微信内部群的机器人使用方式。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"创建机器人流程:"}]},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"创建钉钉/企业微信内部群。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"在群设置中,添加机器人。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"记录下调用机器人的web地址。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"调用机器人的接口需要发送HTTP请求,常用的Python模块如"},{"type":"codeinline","content":[{"type":"text","text":"urllib"}]},{"type":"text","text":"、"},{"type":"codeinline","content":[{"type":"text","text":"requests"}]},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"requests"}]},{"type":"text","text":"模块安装:"},{"type":"codeinline","content":[{"type":"text","text":"pip install requests"}]},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"发送消息流程就2步:"}]},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"构建消息内容数据"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"使用"},{"type":"codeinline","content":[{"type":"text","text":"requests"}]},{"type":"text","text":"发送"},{"type":"codeinline","content":[{"type":"text","text":"post"}]},{"type":"text","text":"请求。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"注意点:"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"为HTTP请求增加头部信息,指明请求内容为"},{"type":"codeinline","content":[{"type":"text","text":"json"}]},{"type":"text","text":"数据。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"提交请求时,需要用"},{"type":"codeinline","content":[{"type":"text","text":"json.dumps()"}]},{"type":"text","text":"方法对数据编码。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"机器人发送消息有频率限制:20条/分钟"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"钉钉机器人使用"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"python"},"content":[{"type":"text","text":"import json\nimport requests\n\ntoken = ''\nkeyword = 'python1024'\nrobot_url = f'https://oapi.dingtalk.com/robot/send?access_token={token}'\nHEADERS = {'Content-Type': 'application/json'}\n# 发送文本消息\ntxt_msg = {\n 'msgtype': 'text', \n 'text': {\n 'content': '欢迎加入Python1024学习群。'\n }, \n 'at': {\n 'atMobiles': [\n '138xxxxxxxx',\n ], \n \"isAtAll\": True\n }\n}\nr = requests.post(robot_url, headers=HEADERS, data=json.dumps(txt_msg))\nprint(r.json())\n# 发送链接信息\nlink_msg = {\n 'msgtype': 'link',\n 'link': {\n 'text': '欢迎加入Python1024,一起探索效率提升。',\n 'title': '程一初的语雀空间',\n 'picUrl': 'https://cdn.nlark.com/yuque/0/2019/png/265643/1550131528833-avatar/b9063fa5-24b2-4360-aaae-8374fa12c8aa.png',\n 'messageUrl': 'https://www.yuque.com/yichu/'\n }\n}\nr = requests.post(robot_url, headers=HEADERS, data=json.dumps(link_msg))\nprint(r.json())\n# 发送Markdown消息\nmd_msg = {\n 'msgtype': 'markdown',\n 'markdown': {\n 'title': '欢迎加入Python1024',\n 'text': '![animate](https://picbed-yichu.oss-cn-shenzhen.aliyuncs.com/picgo/58932a984729f.gif) [视频处理的实用工具](https://www.yuque.com/yichu/selflearning/as6xzv)'\n },\n 'at': {\n \"isAtAll\": True\n }\n}\nr = requests.post(robot_url, headers=HEADERS, data=json.dumps(md_msg))\nprint(r.json())\n# 卡片消息\ncard_msg = {\n 'msgtype': 'actionCard',\n 'actionCard': {\n 'title': '欢迎加入Python1024',\n 'text': '![animate](https://picbed-yichu.oss-cn-shenzhen.aliyuncs.com/picgo/58932a984729f.gif) [视频处理的实用工具](https://www.yuque.com/yichu/selflearning/as6xzv)',\n 'btnOrientation': '0', \n 'singleTitle': '打开空间',\n 'singleURL': 'https://www.yuque.com/yichu/'\n }\n}\nr = requests.post(robot_url, headers=HEADERS, data=json.dumps(card_msg))\nprint(r.json())\n# 选项卡片消息\ncardm_msg = {\n 'msgtype': 'actionCard',\n 'actionCard': {\n 'title': '欢迎加入Python1024',\n 'text': '![animate](https://picbed-yichu.oss-cn-shenzhen.aliyuncs.com/picgo/58932a984729f.gif) [视频处理的实用工具](https://www.yuque.com/yichu/selflearning/as6xzv)',\n 'btnOrientation': '0', \n 'btns': [\n {\n 'title': 'Python自学手册', \n 'actionURL': 'https://www.yuque.com/yichu/selflearning/ux59c6'\n }, \n {\n 'title': 'Python自动办公', \n 'actionURL': 'https://www.yuque.com/yichu/'\n }\n ]\n }\n}\nr = requests.post(robot_url, headers=HEADERS, data=json.dumps(cardm_msg))\nprint(r.json())\n# 发送信息流卡片消息\nfree_card_msg = {\n 'msgtype': 'feedCard',\n 'feedCard': {\n 'links': [\n {\n 'title': '程一初的语雀空间',\n 'messageURL': 'https://www.yuque.com/yichu/',\n 'picURL': 'https://cdn.nlark.com/yuque/0/2019/png/265643/1550131528833-avatar/b9063fa5-24b2-4360-aaae-8374fa12c8aa.png'\n },\n {\n 'title': 'Python1024自动办公系列',\n 'messageURL': 'https://www.yuque.com/yichu/selflearning/ux59c6',\n 'picURL': 'https://cdn.nlark.com/yuque/0/2020/png/265643/1597933041598-ccd75182-aa75-447c-a1f5-7a2685acf88d.png'\n }\n ]\n }\n}\nr = requests.post(robot_url, headers=HEADERS, data=json.dumps(free_card_msg))\nprint(r.json())"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"企业微信内部群机器人使用"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"python"},"content":[{"type":"text","text":"import base64\nimport hashlib\nimport pathlib\nimport json\nimport requests\n\npath = list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/009email')\nfile_path = path.joinpath('avatar.jpg.zip')\nimg_path = path.joinpath('avatar.jpg')\ntoken = ''\nrobot_url = f'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={token}'\nHEADERS = {'Content-Type': 'application/json'}\n# 发送文本消息\ntxt_msg = {\n 'msgtype': 'text', \n 'text': {\n 'content': '欢迎加入Python1024学习群。',\n 'mentioned_list':['ichengplus6','@all'],\n 'mentioned_mobile_list': ['138XXXXXXX']\n }\n}\nr = requests.post(robot_url, headers=HEADERS, data=json.dumps(txt_msg))\nprint(r.json())\n# 发送Markdown消息\nmd_msg = {\n 'msgtype': 'markdown',\n 'markdown': {\n 'content': '1.[Python基础系列](http://mp.weixin.qq.com/mp/homepage?__biz=MzUxNzE4MDkzNw==&hid=2&sn=7d05116c613d0e41797858d59d61ffb2&scene=18#wechat_redirect)\\n\\\n 2.[Python自动办公系列](https://mp.weixin.qq.com/mp/appmsgalbum?action=getalbum&album_id=1477393309697392646&__biz=MzUxNzE4MDkzNw==#wechat_redirect)'\n }\n}\nr = requests.post(robot_url, headers=HEADERS, data=json.dumps(md_msg))\nprint(r.json())\n# 发送图片消息,编码前不超过2M,JPG、PNG\nwith open(img_path, 'rb') as f:\n img_data = f.read()\nb64img = base64.b64encode(img_data)\nmd5 = hashlib.md5()\nmd5.update(img_data)\nimg_msg = {\n 'msgtype': 'image',\n 'image': {\n 'base64': b64img.decode('utf-8'),\n 'md5': md5.hexdigest()\n }\n}\nr = requests.post(robot_url, headers=HEADERS, data=json.dumps(img_msg))\nprint(r.json())\n# 发送图文消息\nnews_msg = {\n 'msgtype': 'news',\n 'news': {\n 'articles': [\n {\n 'title':'Python基础系列',\n 'description': '通往高手的必经之路,看得懂、学得会、用得上。',\n 'url': 'http://mp.weixin.qq.com/mp/homepage?__biz=MzUxNzE4MDkzNw==&hid=2&sn=7d05116c613d0e41797858d59d61ffb2&scene=18#wechat_redirect',\n 'picurl': 'http://mmbiz.qpic.cn/mmbiz_jpg/kSfot6Ez8OicVK0w0bwOkUjYG7I3Sux1icQjjKO7PPMud4YtqoU767mYcrRZNyOicHJiaEFfAGvcz1GWkYWxHxmPpA/0'\n },\n {\n 'title':'Python自动办公系列',\n 'description': '涵盖文本、Word、PPT、Excel、图像、音频、视频、邮件、机器人等常见应用。',\n 'url': 'https://mp.weixin.qq.com/mp/appmsgalbum?action=getalbum&album_id=1477393309697392646&__biz=MzUxNzE4MDkzNw==#wechat_redirect',\n 'picurl': 'http://mmbiz.qpic.cn/mmbiz_jpg/kSfot6Ez8O9sMTzMoHTiaTONYfwAO4ibFc7KaIyMM1xedibr2PHs2e9MD9SuS22v3nZL5b80dd3Ynarkm0fibbEuZA/0'\n }\n ]\n }\n}\nr = requests.post(robot_url, headers=HEADERS, data=json.dumps(news_msg))\nprint(r.json())\n# 发送文件\nmedia_id = ''\nif not media_id:\n # 上传文件\n url = f'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={token}&type=file'\n files = [('file', (file_path.name, open(file_path, 'rb')))]\n r = requests.post(url, files=files)\n j = r.json()\n media_id = j['media_id']\nprint(media_id)\nfile_msg = {\n 'msgtype': 'file',\n 'file': {\n 'media_id': media_id\n }\n}\nr = requests.post(robot_url, headers=HEADERS, data=json.dumps(file_msg))\nprint(r.json())"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"总结"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"本文主要介绍了用Python收发邮件的主要场景,以及钉钉和企业微信机器人的基本使用方法。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在现实的互联网运营中,我们经常会发现一些非官方支持的机器人,如微信机器人、QQ机器人等。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这些都是通过破解官方客户端协议实现,属于非正常使用,受到官方打击和封禁。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"哪里有流量红利,哪里就会有更多技术创新,虽然有时创新的技术非官方所愿。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"目前,钉钉的功能更丰富,但企业微信背靠10亿级月活的微信,也正在发力。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"你认为哪个更有潜力呢?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"欢迎入群交流,前100名免费。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/9c/9c91bab30b2c905274cd45c27d02c27c.png","alt":null,"title":"","style":[{"key":"width","value":"50%"},{"key":"bordertype","value":"none"}],"href":"","fromPaste":false,"pastePass":false}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章