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: <open connection>
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:    <the pop3 server sends message 1>
s:    .
c:    quit
s:    +ok dewey pop3 server signing off (maildrop empty)
c:  <close connection>

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

立即学习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 结尾。对于短(一行)消息,这就是所需要的。对于多行响应,一行上的句点表示消息已完成。

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

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

下载
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: <cadbp03twfokctoak_0p7vv2gb+tzsosd_w4g5nzkks7pdk6cwq@mail.gmail.com>
subject: customize gmail with colors and themes
from: gmail team <mail-noreply@google.com>
to: grok programming <grokprogramming@gmail.com>
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 <https://mail.google.com/mail/#settings/themes>

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<http://support.google.com/mail/bin/answer.py?answer=3d6557&hl=3den&=
utm_source=3dwel-eml&utm_medium=3deml&utm_campaign=3den>
..

--e0cb4e385592f8025004c393f2b4
content-type: text/html; charset=iso-8859-1

more? y/[n]: y

<html>
<font face="arial, helvetica, sans-serif">
<p>to spice up your inbox with colors and themes, check out the themes tab
under settings.</p>

<table cellpadding="0" cellspacing="0">
  <col style="width: 1px;"/>
  <col/>
  <col style="width: 1px;"/>
  <tr>
    <td></td>
    <td height="1px" style="background-color: #ddd"></td>
    <td></td>
  </tr>
  <tr>
    <td style="background-color: #ddd"></td>
    <td background="https://mail.google.com/mail/images/welcome-button-background.png"
        style="background-color: #ddd; background-repeat: repeat-x;
            padding: 10px; font-size: larger">
          <a href="https://mail.google.com/mail/#settings/themes"
            style="font-weight: bold; color: #000; text-decoration: none;
            display: block;">
      customize gmail &#187;</a>
    </td>
    <td style="ba
more? y/[n]: y
ckground-color: #ddd"></td>
  </tr>
 <tr>
    <td></td>
    <td height="1px" style="background-color: #ddd"></td>
    <td></td>
  </tr>
</table>

<p>enjoy!</p>

<p>- the gmail team</p>

@@##@@

<p><font size="-2" color="#999">please note that themes are not available if
you're using internet explorer 6.0. to take advantage of the latest gmail
features, please
<a href="http://support.google.com/mail/bin/answer.py?answer=6557&hl=en&utm_source=wel-eml&utm_medium=eml&utm_campaign=en"><font color="#999">
upgrade to a fully supported browser</font></a>.</font></p>

</font>
</html>

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

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

760

2023.08.03

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

221

2023.09.04

java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1566

2023.10.24

字符串介绍
字符串介绍

字符串是一种数据类型,它可以是任何文本,包括字母、数字、符号等。字符串可以由不同的字符组成,例如空格、标点符号、数字等。在编程中,字符串通常用引号括起来,如单引号、双引号或反引号。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

649

2023.11.24

java读取文件转成字符串的方法
java读取文件转成字符串的方法

Java8引入了新的文件I/O API,使用java.nio.file.Files类读取文件内容更加方便。对于较旧版本的Java,可以使用java.io.FileReader和java.io.BufferedReader来读取文件。在这些方法中,你需要将文件路径替换为你的实际文件路径,并且可能需要处理可能的IOException异常。想了解更多java的相关内容,可以阅读本专题下面的文章。

1228

2024.03.22

php中定义字符串的方式
php中定义字符串的方式

php中定义字符串的方式:单引号;双引号;heredoc语法等等。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

1184

2024.04.29

go语言字符串相关教程
go语言字符串相关教程

本专题整合了go语言字符串相关教程,阅读专题下面的文章了解更多详细内容。

192

2025.07.29

c++字符串相关教程
c++字符串相关教程

本专题整合了c++字符串相关教程,阅读专题下面的文章了解更多详细内容。

131

2025.08.07

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

3

2026.03.11

热门下载

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

精品课程

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

共4课时 | 22.5万人学习

Django 教程
Django 教程

共28课时 | 4.9万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.9万人学习

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

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