使用 Python 与 Gmail POPerver 对话

PHPz
发布: 2024-09-08 06:31:43
原创
1065 人浏览过

Talking to a Gmail POPerver with Python

POP 是一个相对较旧的协议。第一个版本是在 1984 年指定的。至今仍在使用的版本 POP3 是在 1996 年指定的。为了尝试一下,我开始连接到 Gmail POP3 服务器。

第一步是查找 POP3 设置 - 连接到哪个服务器、连接哪个端口。谷歌引导我来到这里,我在那里找到了以下信息。

pop.gmail.com

需要 SSL:是

端口:995

它提到需要 SSL。 25 年前,当我最后一次摆弄 POP 时,我还没有处理过这个问题。我担心这会让人头疼,但事实证明这并不是什么挑战;在 Python 文档的帮助下,我得到了这段代码。

import socket import ssl hostname = 'pop.gmail.com' context = ssl.create_default_context() with socket.create_connection((hostname, 995)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as s: print(s.version())
登录后复制

它连接并告诉我正在使用什么版本的 SSL...或者其他什么。伟大的成功!是时候开始与服务器对话了。

借用 POP3 的官方 RFC,这是客户端和服务器之间的 POP3 对话示例/

C:  S: +OK POP3 server ready <1896.697170952@dbc.mtview.ca.us> C: USER mrose S: +OK mrose is a real hoopy frood C: PASS secret S: +OK mrose's maildrop has 2 messages (320 octets) C: STAT S: +OK 2 320 C: LIST S: +OK 2 messages (320 octets) S: 1 120 S: 2 200 S: . C: RETR 1 S: +OK 120 octets S:  S: . C: QUIT S: +OK dewey POP3 server signing off (maildrop empty) C: 
登录后复制

首先发生的是服务器向客户端发送问候语。友好的。因此,我将添加代码以从服务器接收消息。

当您要求从套接字接收数据时,您必须指定缓冲区大小。文档建议使用 2 的幂,例如 4096。来自服务器的许多响应将同时通过。有些不会;有些则不会。有时来自服务器的消息会在服务器读取时被破坏,并且即使还有更多消息,缓冲区也可能不会填满。

对于 POP3,判断消息是否已传入的方法完全取决于传入的消息。大多数情况下,服务器发送单行文本。 (正如我们稍后将再次看到的,它们在每行末尾都有一个回车符和换行符。)某些可能具有更长响应的消息使用另一种方式来显示它们已完成:单行上的句点就其本身而言。

import socket import ssl hostname = 'pop.gmail.com' context = ssl.create_default_context() with socket.create_connection((hostname, 995)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as s: print(s.version()) data = s.read(4096) print(data)
登录后复制

再次运行,我们收到了问候。又一次巨大的成功!请注意,该行以“rn”结尾——回车符和换行符。

您必须将缓冲区大小传递给读取方法。然后它将有一个缓冲区,其大小可用于从服务器读取数据——但不能保证一次有多少数据进入缓冲区。这意味着协议需要某种方式来指定消息何时完成。有多种可能的策略。 POP 使用两个:对于所有消息,行都以 rn 结尾。对于短(一行)消息,这就是所需要的。对于多行响应,一行上的句点表示消息已完成。

TLSv1.3 b'+OK Gpop ready for requests from 2601:1c0:8301:b590:f408:d66a:3029:16ad dq2mb54750689ivb\r\n'
登录后复制

现在我们需要开始与服务器对话。是时候创建 I/O(或 O/I)循环了;获取一些用户输入并将其发送到服务器。哎呀!我无法直接发送字符串;这给了我一个类型错误。我需要将消息转换为字节。 stringencode() 方法可以做到这一点(默认编码 utf-8 工作正常)。

只是,当我运行它时——哎呀又来了!当我的消息发送到服务器时没有任何反应。因为我忘记了来自客户端的消息也需要以 rn 结尾。另一个微小的调整给了我们:

import socket import ssl hostname = 'pop.gmail.com' context = ssl.create_default_context() with socket.create_connection((hostname, 995)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as s: print(s.version()) while True: data = s.read(4096) print(data) msg = input() + "\r\n" s.send(msg.encode())
登录后复制

太好了,现在我可以尝试登录了!

TLSv1.3 b'+OK Gpop ready for requests from 2601:1c0:8301:b590:f408:d66a:3029:16ad g4mb5147337iow\r\n' USER grokprogramming b'+OK send PASS\r\n' PASS trustno1 b'-ERR [AUTH] Application-specific password required: https://support.google.com/accounts/answer/185833\r\n'
登录后复制

好的,点击该链接后,我将进入一个可以设置应用程序特定密码的页面。我遇到的一个潜在的障碍是:据我所知,您的帐户必须启用双因素身份验证,以便您能够创建应用程序特定的密码。为什么我在我们的 Lorde 2024 年开启双因素身份验证?我不能说。我现在知道了。

有了应用程序特定的密码(注意去掉空格),我就可以登录了!然后我将发出 STAT 命令,它会告诉我有多少条消息以及它们的总大小。之后,我将发出 LIST 命令,该命令将返回一个消息列表,其中包含每条消息的 ID 和大小。

TLSv1.3 b'+OK Gpop ready for requests from 2601:1c0:8301:b590:f408:d66a:3029:16ad e18mb76868856iow\r\n' USER grokprogramming b'+OK send PASS\r\n' PASS baygdsgkmihkckrb b'+OK Welcome.\r\n' STAT b'+OK 263 14191565\r\n' LIST b'+OK 263 messages (14191565 bytes)\r\n1 2778\r\n2 2947\r\n3 6558\r\n4 9864\r\n5 35997\r\n6 45462\r\n7 45462\r\n8 63894\r\n9 11487\r\n10 74936\r\n11 74925\r\n12 11632\r\n13 32392\r\n14 74997\r\n15 51961\r\n16 15375\r\n17 46513\r\n18 21519\r\n19 15966\r\n20 27258\r\n21 28503\r\n22 35615\r\n23 86353\r\n24 280'
登录后复制

我在代码中遇到了一个错误。 LIST 的响应跨越多行,在这种情况下,将需要多次缓冲区读取。整条消息将以单独一行的句点结束。在这里,我已经收到了一个缓冲区的消息,现在我必须按回车键并向服务器发送一条空白消息,以便代码前进到循环的下一次迭代并再次从缓冲区读取。

我将调整代码,以便用户始终可以选择是否再次从缓冲区读取。我还将最终解码从服务器传入的字节,以便文本呈现得更好。

import socket import ssl hostname = 'pop.gmail.com' context = ssl.create_default_context() with socket.create_connection((hostname, 995)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as s: print(s.version()) while True: data = s.read(4096) print(data.decode()) while input("more? y/[n]: ") == "y": data = s.read(4096) print(data.decode()) msg = input("> ") + "\r\n" s.send(msg.encode())
登录后复制

这是一个完整的会话,包括检索电子邮件和发送断开连接消息。

> USER grokprogramming +OK send PASS more? y/[n]: > PASS trustno1 +OK Welcome. more? y/[n]: > STAT +OK 263 14191565 more? y/[n]: > LIST +OK 263 messages (14191565 bytes) 1 2778 2 2947 3 6558 <...> 260 41300 261 114059 262 174321 263 39206 . more? y/[n]: > RETR 1 +OK message follows MIME-Version: 1.0 Received: by 10.76.81.230; Thu, 28 Jun 2012 20:21:50 -0700 (PDT) Date: Thu, 28 Jun 2012 20:21:50 -0700 Message-ID:  Subject: Customize Gmail with colors and themes From: Gmail Team  To: Grok Programming  Content-Type: multipart/alternative; boundary=e0cb4e385592f8025004c393f2b4 --e0cb4e385592f8025004c393f2b4 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable To spice up your inbox with colors and themes, check out the Themes tab under Settings. Customize Gmail =BB  Enjoy! - The Gmail Team [image: Themes thumbnails] Please note that Themes are not available if you're using Internet Explorer 6.0. To take advantage of the latest Gmail features, please upgrade to a fully supported browser .. --e0cb4e385592f8025004c393f2b4 Content-Type: text/html; charset=ISO-8859-1 more? y/[n]: y   

To spice up your inbox with colors and themes, check out the Themes tab under Settings.

Customize Gmail »

Enjoy!

- The Gmail Team

Themes thumbnails

Please note that Themes are not available if you're using Internet Explorer 6.0. To take advantage of the latest Gmail features, please upgrade to a fully supported browser.

--e0cb4e385592f8025004c393f2b4-- . more? y/[n]: > QUIT +OK Farewell. more? y/[n]: >
登录后复制

Yet another great success! I was able to log in to the POP3 server and retrieve a message. The script in its current state is pretty flexible, but it requires a lot of work from the user. I'll make a few final tweaks to make interacting with the POP3 server a little easier: if the user starts a message to the server with a "!" it will be stripped out, but the script will read in data from the server until it gets to a period on a line by itself -- in other words, for commands with long responses. No "!" and the script will read in a single line, looking for the \r\n characters.

import socket import ssl hostname = 'pop.gmail.com' context = ssl.create_default_context() def read_until(s, eom): # read into the buffer at least once data = s.read(4096) # continue reading until end of message while data[-len(eom):] != eom: data += s.read(4096) # return incoming bytes decoded to a string return data.decode() def read_single_line(s): return read_until(s, b"\r\n") def read_muli_line(s): return read_until(s, b"\r\n.\r\n") with socket.create_connection((hostname, 995)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as s: print(s.version()) print(read_single_line(s)) msg = input("> ") # empty msg will close connection while msg != "": if msg[0] == "!": msg = msg[1:] long = True else: long = False msg += "\r\n" s.send(msg.encode()) if long: print(read_muli_line(s)) else: print(read_single_line(s)) msg = input("> ") s.close()
登录后复制

以上是使用 Python 与 Gmail POPerver 对话的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!