Python-network-programming-python-imap

提供:Dev Guides
移動先:案内、検索

Python-IMAP

IMAPは、電子メールをダウンロードしない電子メール取得プロトコルです。 それらを読み取って表示するだけです。 これは、低帯域幅条件で非常に便利です。 imaplib と呼ばれるPythonのクライアント側ライブラリは、imapプロトコルを介してメールにアクセスするために使用されます。

*IMAP* は* Internet Mail Access Protocolの略です。1986年に最初に提案されました。

キーポイント:

  • IMAPを使用すると、クライアントプログラムは、ローカルコンピューターにダウンロードせずにサーバー上の電子メールメッセージを操作できます。
  • 電子メールは、リモートサーバーによって保持および維持されます。
  • これにより、ダウンロードなどのアクションを実行したり、メールを読み取らずにメールを削除したり、メールボックスと呼ばれるリモートメッセージフォルダーを作成、操作、削除したりできます。
  • IMAPを使用すると、ユーザーは電子メールを検索できます。
  • 複数のメールサーバー上の複数のメールボックスに同時にアクセスできます。

IMAPコマンド

次の表に、IMAPコマンドの一部を示します。

S.N. Command Description
1 IMAP_LOGINThis command opens the connection.
2 CAPABILITYThis command requests for listing the capabilities that the server supports.
3 NOOPThis command is used as a periodic poll for new messages or message status updates during a period of inactivity.
4 SELECTThis command helps to select a mailbox to access the messages.
5 EXAMINEIt is same as SELECT command except no change to the mailbox is permitted.
6 CREATEIt is used to create mailbox with a specified name.
7 DELETEIt is used to permanently delete a mailbox with a given name.
8 RENAMEIt is used to change the name of a mailbox.
9 LOGOUTThis command informs the server that client is done with the session. The server must send BYE untagged response before the OK response and then close the network connection.

例

以下の例では、ユーザー資格情報を使用してGmailサーバーにログインします。 次に、受信ボックスにメッセージを表示することを選択します。 forループを使用して、フェッチしたメッセージを1つずつ表示し、最終的に接続を閉じます。

import imaplib
import pprint

imap_host = 'imap.gmail.com'
imap_user = '[email protected]'
imap_pass = 'password'

# connect to host using SSL
imap = imaplib.IMAP4_SSL(imap_host)

## login to server
imap.login(imap_user, imap_pass)

imap.select('Inbox')

tmp, data = imap.search(None, 'ALL')
for num in data[0].split():
    tmp, data = imap.fetch(num, '(RFC822)')
    print('Message: {0}\n'.format(num))
    pprint.pprint(data[0][1])
    break
imap.close()

メールボックスの構成に応じて、メールが表示されます。