0

0

使用 Python 与 Gmail POPerver 对话

王林

王林

发布时间:2024-09-08 10:18:39

|

572人浏览过

|

来源于dev.to

转载

使用 python 与 gmail poperver 对话

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:  

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

立即学习Python免费学习笔记(深入)”;

当您要求从套接字接收数据时,您必须指定缓冲区大小。文档建议使用 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 工作正常)。

商务通(在线客服系统)
商务通(在线客服系统)

一款无需安装的即时交流系统,只需申请一个帐号,将一段代码嵌入贵站网页中,就可以让客服人员发现所有到达您网站的访客,而且可以看到访客的来源、使用的搜索引擎等,您可以主动发起对话与访客沟通,进行产品推销,从而大大提高产品销售成功率。 还是一款协同管理软件,在保持与客户信息通畅的同时,也保持公司内部之间的信息交流,从而提高企业的工作效率和客户服务质量。 管理员帐号:biiz.cn 密码:biiz.cn

下载

只是,当我运行它时——哎呀又来了!当我的消息发送到服务器时没有任何反应。因为我忘记了来自客户端的消息也需要以 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

@@##@@

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]: >

又一次巨大的成功!我能够登录 pop3 服务器并检索邮件。当前状态下的脚本非常灵活,但需要用户做大量工作。我将进行一些最后的调整,以使与 pop3 服务器的交互更加容易:如果用户使用“!”开始向服务器发送消息。它会被删除,但脚本将从服务器读取数据,直到它自己到达一行上的句点 - 换句话说,对于具有长响应的命令。不 ”!”脚本将在一行中读取,寻找 rn 字符。

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()
themes thumbnails

相关专题

更多
python开发工具
python开发工具

php中文网为大家提供各种python开发工具,好的开发工具,可帮助开发者攻克编程学习中的基础障碍,理解每一行源代码在程序执行时在计算机中的过程。php中文网还为大家带来python相关课程以及相关文章等内容,供大家免费下载使用。

715

2023.06.15

python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

626

2023.07.20

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

739

2023.07.25

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

617

2023.07.31

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

1235

2023.08.03

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

547

2023.08.04

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

575

2023.08.04

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

699

2023.08.11

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 0.6万人学习

Django 教程
Django 教程

共28课时 | 2.6万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.0万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号