使用 Python 與 Gmail POPerver 對話

PHPz
發布: 2024-09-08 06:31:43
原創
1191 人瀏覽過

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: <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>
登入後複製

首先發生的是伺服器傳送問候語給客戶端。友好的。因此,我將添加程式碼以從伺服器接收訊息。

當您要求從套接字接收資料時,您必須指定緩衝區大小。文件建議使用 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: <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>

<img width="398" height="256" src="https://mail.google.com/mail/images/gmail_themes_2.png" alt="Themes thumbnails" />

<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]: 
> 
登入後複製

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學習者快速成長!