mailbox
--- 様々な形式のメールボックス操作¶
ソースコード: Lib/mailbox.py
This module defines two classes, Mailbox
and Message
, for
accessing and manipulating on-disk mailboxes and the messages they contain.
Mailbox
offers a dictionary-like mapping from keys to messages.
Message
extends the email.message
module's
Message
class with format-specific state and behavior.
Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
参考
email
モジュールメッセージの表現と操作。
Mailbox
objects¶
- class mailbox.Mailbox¶
メールボックス。内容を確認したり変更したりできます。
The
Mailbox
class defines an interface and is not intended to be instantiated. Instead, format-specific subclasses should inherit fromMailbox
and your code should instantiate a particular subclass.The
Mailbox
interface is dictionary-like, with small keys corresponding to messages. Keys are issued by theMailbox
instance with which they will be used and are only meaningful to thatMailbox
instance. A key continues to identify a message even if the corresponding message is modified, such as by replacing it with another message.Messages may be added to a
Mailbox
instance using the set-like methodadd()
and removed using adel
statement or the set-like methodsremove()
anddiscard()
.Mailbox
interface semantics differ from dictionary semantics in some noteworthy ways. Each time a message is requested, a new representation (typically aMessage
instance) is generated based upon the current state of the mailbox. Similarly, when a message is added to aMailbox
instance, the provided message representation's contents are copied. In neither case is a reference to the message representation kept by theMailbox
instance.The default
Mailbox
iterator iterates over message representations, not keys as the defaultdictionary
iterator does. Moreover, modification of a mailbox during iteration is safe and well-defined. Messages added to the mailbox after an iterator is created will not be seen by the iterator. Messages removed from the mailbox before the iterator yields them will be silently skipped, though using a key from an iterator may result in aKeyError
exception if the corresponding message is subsequently removed.警告
Be very cautious when modifying mailboxes that might be simultaneously changed by some other process. The safest mailbox format to use for such tasks is
Maildir
; try to avoid using single-file formats such asmbox
for concurrent writing. If you're modifying a mailbox, you must lock it by calling thelock()
andunlock()
methods before reading any messages in the file or making any changes by adding or deleting a message. Failing to lock the mailbox runs the risk of losing messages or corrupting the entire mailbox.Mailbox
instances have the following methods:- add(message)¶
メールボックスに message を追加し、それに割り当てられたキーを返します。
引数 message は
Message
インスタンス、email.message.Message
インスタンス、文字列、バイト文字列、ファイル風オブジェクト (バイナリモードで開かれていなければなりません) を使えます。 message が適切な形式に特化したMessage
サブクラスのインスタンス (例えばメールボックスがmbox
インスタンスのときのmboxMessage
インスタンス) であれば、形式ごとの情報が利用されます。そうでなければ、形式ごとに必要な情報は適当なデフォルトが使われます。バージョン 3.2 で変更: バイナリ入力のサポートが追加されました。
- remove(key)¶
- __delitem__(key)¶
- discard(key)¶
メールボックスから key に対応するメッセージを削除します。
対応するメッセージが無い場合、メソッドが
remove()
または__delitem__()
として呼び出されている時はKeyError
例外が送出されます。しかし、discard()
として呼び出されている場合は例外は発生しません。基づいているメールボックス形式が別のプロセスからの平行した変更をサポートしているならば、このdiscard()
の振る舞いの方が好まれるかもしれません。
- __setitem__(key, message)¶
key に対応するメッセージを message で置き換えます。 key に対応しているメッセージが既に無くなっている場合
KeyError
例外が送出されます。add()
と同様に、引数の message にはMessage
インスタンス、email.message.Message
インスタンス、文字列、バイト文字列、ファイル風オブジェクト (バイナリモードで開かれていなければなりません) を使えます。 message が適切な形式に特化したMessage
サブクラスのインスタンス (例えばメールボックスがmbox
インスタンスのときのmboxMessage
インスタンス) であれば、形式ごとの情報が利用されます。そうでなければ、現在 key に対応するメッセージの形式ごとの情報が変更されずに残ります。
- keys()¶
The same as
iterkeys()
, except that alist
is returned rather than an iterator
- itervalues()¶
- __iter__()¶
Return an iterator over representations of all messages. The messages are represented as instances of the appropriate format-specific
Message
subclass unless a custom message factory was specified when theMailbox
instance was initialized.注釈
__iter__()
は辞書のそれのようにキーについてのイテレータではありません。
- values()¶
The same as
itervalues()
, except that alist
is returned rather than an iterator
- iteritems()¶
Return an iterator over (key, message) pairs, where key is a key and message is a message representation. The messages are represented as instances of the appropriate format-specific
Message
subclass unless a custom message factory was specified when theMailbox
instance was initialized.
- items()¶
The same as
iteritems()
, except that alist
of pairs is returned rather than an iterator of pairs.
- get(key, default=None)¶
- __getitem__(key)¶
Return a representation of the message corresponding to key. If no such message exists, default is returned if the method was called as
get()
and aKeyError
exception is raised if the method was called as__getitem__()
. The message is represented as an instance of the appropriate format-specificMessage
subclass unless a custom message factory was specified when theMailbox
instance was initialized.
- get_message(key)¶
key に対応するメッセージの表現を形式ごとの
Message
サブクラスのインスタンスとして返します。もし対応するメッセージが存在しなければKeyError
例外が送出されます。
- get_bytes(key)¶
key に対応するメッセージのバイト列を返すか、そのようなメッセージが存在しない場合は
KeyError
例外を送出します。Added in version 3.2.
- get_string(key)¶
key に対応するメッセージの文字列表現を返すか、そのようなメッセージが存在しない場合は
KeyError
例外を送出します。このメッセージはemail.message.Message
を通して処理されて7ビットクリーンな表現へ変換されます。
- get_file(key)¶
Return a file-like representation of the message corresponding to key, or raise a
KeyError
exception if no such message exists. The file-like object behaves as if open in binary mode. This file should be closed once it is no longer needed.バージョン 3.2 で変更: The file object really is a binary file; previously it was incorrectly returned in text mode. Also, the file-like object now supports the context manager protocol: you can use a
with
statement to automatically close it.注釈
Unlike other representations of messages, file-like representations are not necessarily independent of the
Mailbox
instance that created them or of the underlying mailbox. More specific documentation is provided by each subclass.
- __contains__(key)¶
key がメッセージに対応していれば
True
を、そうでなければFalse
を返します。
- __len__()¶
メールボックス中のメッセージ数を返します。
- clear()¶
メールボックスから全てのメッセージを削除します。
- pop(key, default=None)¶
Return a representation of the message corresponding to key and delete the message. If no such message exists, return default. The message is represented as an instance of the appropriate format-specific
Message
subclass unless a custom message factory was specified when theMailbox
instance was initialized.
- popitem()¶
Return an arbitrary (key, message) pair, where key is a key and message is a message representation, and delete the corresponding message. If the mailbox is empty, raise a
KeyError
exception. The message is represented as an instance of the appropriate format-specificMessage
subclass unless a custom message factory was specified when theMailbox
instance was initialized.
- update(arg)¶
Parameter arg should be a key-to-message mapping or an iterable of (key, message) pairs. Updates the mailbox so that, for each given key and message, the message corresponding to key is set to message as if by using
__setitem__()
. As with__setitem__()
, each key must already correspond to a message in the mailbox or else aKeyError
exception will be raised, so in general it is incorrect for arg to be aMailbox
instance.注釈
辞書と違い、キーワード引数はサポートされていません。
- flush()¶
Write any pending changes to the filesystem. For some
Mailbox
subclasses, changes are always written immediately andflush()
does nothing, but you should still make a habit of calling this method.
- lock()¶
メールボックスの排他的アドバイザリロックを取得し、他のプロセスが変更しないようにします。ロックが取得できない場合
ExternalClashError
が送出されます。ロック機構はメールボックス形式によって変わります。メールボックスの内容に変更を加えるときは いつも ロックを掛けるべきです。
- unlock()¶
メールボックスのロックが存在する場合は解放します。
- close()¶
Flush the mailbox, unlock it if necessary, and close any open files. For some
Mailbox
subclasses, this method does nothing.
Maildir
objects¶
- class mailbox.Maildir(dirname, factory=None, create=True)¶
Maildir 形式のメールボックスのための
Mailbox
のサブクラス。パラメータ factory は呼び出し可能オブジェクトで (バイナリモードで開かれているかのように振る舞う)ファイル風メッセージ表現を受け付けて好みの表現を返すものです。 factory がNone
ならば、MaildirMessage
がデフォルトのメッセージ表現として使われます。 create がTrue
ならばメールボックスが存在しないときには作成します。create が
True
で、パス dirname が存在する場合、ディレクトリレイアウトを検証せずに既存の maildir として扱います。path ではなく dirname と命名される歴史的な理由のためです。
Maildir はディレクトリ型のメールボックス形式でメール転送エージェント qmail 用に発明され、現在では多くの他のプログラムでもサポートされているものです。Maildir メールボックス中のメッセージは共通のディレクトリ構造の下で個別のファイルに保存されます。このデザインにより、Maildir メールボックスは複数の無関係のプログラムからデータを失うことなくアクセスしたり変更したりできます。そのためロックは不要です。
Maildir メールボックスには三つのサブディレクトリ
tmp
,new
,cur
があります。メッセージはまずtmp
サブディレクトリに瞬間的に作られた後、new
サブディレクトリに移動されて配送を完了します。メールユーザエージェントが引き続いてcur
サブディレクトリにメッセージを移動しメッセージの状態についての情報をファイル名に追加される特別な "info" セクションに保存することができます。Folders of the style introduced by the Courier mail transfer agent are also supported. Any subdirectory of the main mailbox is considered a folder if
'.'
is the first character in its name. Folder names are represented byMaildir
without the leading'.'
. Each folder is itself a Maildir mailbox but should not contain other folders. Instead, a logical nesting is indicated using'.'
to delimit levels, e.g., "Archived.2005.07".- colon¶
本来の Maildir 仕様ではある種のメッセージのファイル名にコロン (
':'
) を使う必要があります。しかしながら、オペレーティングシステムによってはこの文字をファイル名に含めることができないことがあります。そういった環境で Maildir のような形式を使いたい場合、代わりに使われる文字を指定する必要があります。感嘆符 ('!'
) を使うのが一般的な選択です。以下の例を見てください:import mailbox mailbox.Maildir.colon = '!'
The
colon
attribute may also be set on a per-instance basis.
Maildir
instances have all of the methods ofMailbox
in addition to the following:- list_folders()¶
全てのフォルダ名のリストを返します。
- get_folder(folder)¶
Return a
Maildir
instance representing the folder whose name is folder. ANoSuchMailboxError
exception is raised if the folder does not exist.
- add_folder(folder)¶
Create a folder whose name is folder and return a
Maildir
instance representing it.
- remove_folder(folder)¶
名前が folder であるフォルダを削除します。もしフォルダに一つでもメッセージが含まれていれば
NotEmptyError
例外が送出されフォルダは削除されません。
- clean()¶
過去36時間以内にアクセスされなかったメールボックス内の一時ファイルを削除します。Maildir 仕様はメールを読むプログラムはときどきこの作業をすべきだとしています。
Some
Mailbox
methods implemented byMaildir
deserve special remarks:- add(message)¶
- __setitem__(key, message)¶
- update(arg)¶
警告
これらのメソッドは一意的なファイル名をプロセスIDに基づいて生成します。複数のスレッドを使う場合は、同じメールボックスを同時に操作しないようにスレッド間で調整しておかないと検知されない名前の衝突が起こりメールボックスを壊すかもしれません。
- flush()¶
Maildir メールボックスへの変更は即時に適用されるので、このメソッドは何もしません。
- close()¶
Maildir
instances do not keep any open files and the underlying mailboxes do not support locking, so this method does nothing.
- get_file(key)¶
ホストのプラットフォームによっては、返されたファイルが開いている間、元になったメッセージを変更したり削除したりできない場合があります。
参考
- Courier の maildir マニュアルページ
Maildir 形式の仕様。フォルダをサポートする一般的な拡張について記述されています。
- Using maildir format
Maildir 形式の発明者による注意書き。更新された名前生成規則と "info" の解釈についても含まれます。
mbox
objects¶
- class mailbox.mbox(path, factory=None, create=True)¶
mbox 形式のメールボックスのための
Mailbox
のサブクラス。パラメータ factory は呼び出し可能オブジェクトで (バイナリモードで開かれているかのように振る舞う)ファイル風メッセージ表現を受け付けて好みの表現を返すものです。 factory がNone
ならば、mboxMessage
がデフォルトのメッセージ表現として使われます。 create がTrue
ならばメールボックスが存在しないときには作成します。mbox 形式は Unixシステム上でメールを保存する古くからある形式です。mbox メールボックスでは全てのメッセージが一つのファイルに保存されておりそれぞれのメッセージは "From " という5文字で始まる行を先頭に付けられています。
Several variations of the mbox format exist to address perceived shortcomings in the original. In the interest of compatibility,
mbox
implements the original format, which is sometimes referred to as mboxo. This means that the Content-Length header, if present, is ignored and that any occurrences of "From " at the beginning of a line in a message body are transformed to ">From " when storing the message, although occurrences of ">From " are not transformed to "From " when reading the message.Some
Mailbox
methods implemented bymbox
deserve special remarks:
参考
- tin の mbox マニュアルページ
mbox 形式の仕様でロックについての詳細を含む。
- Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad
バリエーションの一つではなくオリジナルの mbox を使う理由。
- "mbox" は相互に互換性を持たないいくつかのメールボックスフォーマットの集まりです
mbox バリエーションの歴史。
MH
objects¶
- class mailbox.MH(path, factory=None, create=True)¶
MH 形式のメールボックスのための
Mailbox
のサブクラス。パラメータ factory は呼び出し可能オブジェクトで (バイナリモードで開かれているかのように振る舞う)ファイル風メッセージ表現を受け付けて好みの表現を返すものです。 factory がNone
ならば、MHMessage
がデフォルトのメッセージ表現として使われます。 create がTrue
ならばメールボックスが存在しないときには作成します。MH はディレクトリに基づいたメールボックス形式で MH Message Handling System というメールユーザエージェントのために発明されました。 MH メールボックス中のそれぞれのメッセージは一つのファイルとして収められています。 MH メールボックスにはメッセージの他に別の MH メールボックス (フォルダ と呼ばれます)を含んでもかまいません。フォルダは無限にネストできます。 MH メールボックスにはもう一つ シーケンス という名前付きのリストでメッセージをサブフォルダに移動することなく論理的に分類するものがサポートされています。シーケンスは各フォルダの
.mh_sequences
というファイルで定義されます。The
MH
class manipulates MH mailboxes, but it does not attempt to emulate all of mh's behaviors. In particular, it does not modify and is not affected by thecontext
or.mh_profile
files that are used by mh to store its state and configuration.MH
instances have all of the methods ofMailbox
in addition to the following:- list_folders()¶
全てのフォルダ名のリストを返します。
- get_folder(folder)¶
Return an
MH
instance representing the folder whose name is folder. ANoSuchMailboxError
exception is raised if the folder does not exist.
- add_folder(folder)¶
Create a folder whose name is folder and return an
MH
instance representing it.
- remove_folder(folder)¶
名前が folder であるフォルダを削除します。もしフォルダに一つでもメッセージが含まれていれば
NotEmptyError
例外が送出されフォルダは削除されません。
- get_sequences()¶
folder という名前のフォルダを削除します。フォルダにメッセージが一つでも残っていれば、
NotEmptyError
例外が送出されフォルダは削除されません。
- set_sequences(sequences)¶
シーケンス名をキーのリストに対応付ける辞書を返します。シーケンスが一つもなければ空の辞書を返します。
- pack()¶
メールボックス中のシーケンスを
get_sequences()
で返されるような名前とキーのリストを対応付ける辞書 sequences に基づいて再定義します。注釈
番号付けの間隔を詰める必要に応じてメールボックス中のメッセージの名前を付け替えます。シーケンスのリストのエントリもそれに応じて更新されます。
Some
Mailbox
methods implemented byMH
deserve special remarks:- remove(key)¶
- __delitem__(key)¶
- discard(key)¶
これらのメソッドはメッセージを直ちに削除します。名前の前にコンマを付加してメッセージに削除の印を付けるという MH の規約は使いません。
- lock()¶
- unlock()¶
Three locking mechanisms are used---dot locking and, if available, the
flock()
andlockf()
system calls. For MH mailboxes, locking the mailbox means locking the.mh_sequences
file and, only for the duration of any operations that affect them, locking individual message files.
- get_file(key)¶
ホストプラットフォームにより、ファイルが開かれたままの場合はメッセージを削除することができない場合があります。
- flush()¶
MH メールボックスへの変更は即時に適用されますのでこのメソッドは何もしません。
参考
- nmh - Message Handling System
mh の改良版である nmh のホームページ。
- MH & nmh: Email for Users & Programmers
GPLライセンスの mh および nmh の本で、このメールボックス形式についての情報があります。
Babyl
objects¶
- class mailbox.Babyl(path, factory=None, create=True)¶
Babyl 形式のメールボックスのための
Mailbox
のサブクラス。パラメータ factory は呼び出し可能オブジェクトで (バイナリモードで開かれているかのように振る舞う)ファイル風メッセージ表現を受け付けて好みの表現を返すものです。 factory がNone
ならば、BabylMessage
がデフォルトのメッセージ表現として使われます。 create がTrue
ならばメールボックスが存在しないときには作成します。Babyl は単一ファイルのメールボックス形式で Emacs に付属している Rmail メールユーザエージェントで使われているものです。メッセージの開始は Control-Underscore (
'\037'
) および Control-L ('\014'
) の二文字を含む行で示されます。メッセージの終了は次のメッセージの開始または最後のメッセージの場合には Control-Underscore を含む行で示されます。Babyl メールボックス中のメッセージには二つのヘッダのセット、オリジナルヘッダといわゆる可視ヘッダ、があります。可視ヘッダは典型的にはオリジナルヘッダの一部を分り易いように再整形したり短くしたりしたものです。 Babyl メールボックス中のそれぞれのメッセージには ラベル というそのメッセージについての追加情報を記録する短い文字列のリストを伴い、メールボックス中に見出されるユーザが定義した全てのラベルのリストは Babyl オプションセクションに保持されます。
Babyl
instances have all of the methods ofMailbox
in addition to the following:- get_labels()¶
メールボックスで使われているユーザが定義した全てのラベルのリストを返します。
注釈
メールボックスにどのようなラベルが存在するかを決めるのに、Babyl オプションセクションのリストを参考にせず、実際のメッセージを捜索しますが、Babyl セクションもメールボックスが変更されたときにはいつでも更新されます。
Some
Mailbox
methods implemented byBabyl
deserve special remarks:- get_file(key)¶
Babyl メールボックスにおいて、メッセージのヘッダはボディと繋がって格納されていません。ファイル風の表現を生成するために、ヘッダとボディがファイルと同じ API を持つ
io.BytesIO
インスタンスに一緒にコピーされます。その結果、ファイル風オブジェクトは元にしているメールボックスとは真に独立していますが、文字列表現と比べてメモリーを節約することにはなりません。
参考
- Format of Version 5 Babyl Files
Babyl 形式の仕様。
- Reading Mail with Rmail
Rmail のマニュアルで Babyl のセマンティクスについての情報も少しある。
MMDF
objects¶
- class mailbox.MMDF(path, factory=None, create=True)¶
MMDF 形式のメールボックスのための
Mailbox
のサブクラス。パラメータ factory は呼び出し可能オブジェクトで (バイナリモードで開かれているかのように振る舞う)ファイル風メッセージ表現を受け付けて好みの表現を返すものです。 factory がNone
ならば、MMDFMessage
がデフォルトのメッセージ表現として使われます。 create がTrue
ならばメールボックスが存在しないときには作成します。MMDF は単一ファイルのメールボックス形式で Multichannel Memorandum Distribution Facility というメール転送エージェント用に発明されたものです。各メッセージは mbox と同様の形式で収められますが、前後を4つの Control-A (
'\001'
) を含む行で挟んであります。mbox 形式と同じようにそれぞれのメッセージの開始は "From " の5文字を含む行で示されますが、それ以外の場所での "From " は格納の際 ">From " には変えられません。それは追加されたメッセージ区切りによって新たなメッセージの開始と見間違うことが避けられるからです。Some
Mailbox
methods implemented byMMDF
deserve special remarks:
参考
- mmdf man page from tin
ニュースリーダ tin のドキュメント中の MMDF 形式仕様。
- MMDF
Multichannel Memorandum Distribution Facility についてのウィキペディアの記事。
Message
objects¶
- class mailbox.Message(message=None)¶
A subclass of the
email.message
module'sMessage
. Subclasses ofmailbox.Message
add mailbox-format-specific state and behavior.If message is omitted, the new instance is created in a default, empty state. If message is an
email.message.Message
instance, its contents are copied; furthermore, any format-specific information is converted insofar as possible if message is aMessage
instance. If message is a string, a byte string, or a file, it should contain an RFC 2822-compliant message, which is read and parsed. Files should be open in binary mode, but text mode files are accepted for backward compatibility.サブクラスにより提供される形式ごとの状態と動作は様々ですが、一般に或るメールボックスに固有のものでないプロパティだけがサポートされます(おそらくプロパティのセットはメールボックス形式ごとに固有でしょうが)。例えば、単一ファイルメールボックス形式におけるファイルオフセットやディレクトリ式メールボックス形式におけるファイル名は保持されません、というのもそれらは元々のメールボックスにしか適用できないからです。しかし、メッセージがユーザに読まれたかどうかあるいは重要だとマークされたかどうかという状態は保持されます、というのはそれらはメッセージ自体に適用されるからです。
There is no requirement that
Message
instances be used to represent messages retrieved usingMailbox
instances. In some situations, the time and memory required to generateMessage
representations might not be acceptable. For such situations,Mailbox
instances also offer string and file-like representations, and a custom message factory may be specified when aMailbox
instance is initialized.
MaildirMessage
objects¶
- class mailbox.MaildirMessage(message=None)¶
Maildir 固有の動作をするメッセージ。引数 message は
Message
のコンストラクタと同じ意味を持ちます。通常、メールユーザエージェントは
new
サブディレクトリにある全てのメッセージをユーザが最初にメールボックスを開くか閉じるかした後でcur
サブディレクトリに移動し、メッセージが実際に読まれたかどうかを記録します。cur
にある各メッセージには状態情報を保存するファイル名に付け加えられた "info" セクションがあります。(メールリーダの中には "info" セクションをnew
にあるメッセージに付けることもあります。) "info" セクションには二つの形式があります。一つは "2," の後に標準化されたフラグのリストを付けたもの (たとえば "2,FR")、もう一つは "1," の後にいわゆる実験的情報を付け加えるものです。 Maildir の標準的なフラグは以下の通りです:Flag
意味
説明
D
ドラフト(Draft)
作成中
F
フラグ付き(Flagged)
重要とされたもの
P
通過(Passed)
転送、再送またはバウンス
R
返答済み(Replied)
返答されたもの
S
既読(Seen)
読んだもの
T
ごみ(Trashed)
削除予定とされたもの
MaildirMessage
instances offer the following methods:- get_subdir()¶
"new" (メッセージが
new
サブディレクトリに保存されるべき場合) または "cur" (メッセージがcur
サブディレクトリに保存されるべき場合)のどちらかを返します。注釈
メッセージは通常メールボックスがアクセスされた後、メッセージが読まれたかどうかに関わらず
new
からcur
に移動されます。メッセージmsg
は"S" in msg.get_flags()
がTrue
ならば読まれています。
- set_subdir(subdir)¶
メッセージが保存されるべきサブディレクトリをセットします。パラメータ subdir は "new" または "cur" のいずれかでなければなりません。
- get_flags()¶
現在セットされているフラグを特定する文字列を返します。メッセージが標準 Maildir 形式に準拠しているならば、結果はアルファベット順に並べられたゼロまたは1回の
'D'
、'F'
、'P'
、'R'
、'S'
、'T'
をつなげたものです。空文字列が返されるのはフラグが一つもない場合、または "info" が実験的セマンティクスを使っている場合です。
- set_flags(flags)¶
flags で指定されたフラグをセットし、他のフラグは下ろします。
- add_flag(flag)¶
flag で指定されたフラグをセットしますが他のフラグは変えません。一度に二つ以上のフラグをセットすることは、flag に2文字以上の文字列を指定すればできます。現在の "info" はフラグの代わりに実験的情報を使っていても上書きされます。
- remove_flag(flag)¶
flag で指定されたフラグを下ろしますが他のフラグは変えません。一度に二つ以上のフラグを取り除くことは、flag に2文字以上の文字列を指定すればできます。"info" がフラグの代わりに実験的情報を使っている場合は現在の "info" は書き換えられません。
- get_date()¶
メッセージの配送日時をエポックからの秒数を表わす浮動小数点数で返します。
- set_date(date)¶
メッセージの配送日時を date にセットします。date はエポックからの秒数を表わす浮動小数点数です。
- get_info()¶
メッセージの "info" を含む文字列を返します。このメソッドは実験的 (即ちフラグのリストでない) "info" にアクセスし、また変更するのに役立ちます。
- set_info(info)¶
"info" に文字列 info をセットします。
When a MaildirMessage
instance is created based upon an
mboxMessage
or MMDFMessage
instance, the Status
and X-Status headers are omitted and the following conversions
take place:
結果の状態 |
|
---|---|
"cur" サブディレクトリ |
O フラグ |
F フラグ |
F フラグ |
R フラグ |
A フラグ |
S フラグ |
R フラグ |
T フラグ |
D フラグ |
When a MaildirMessage
instance is created based upon an
MHMessage
instance, the following conversions take place:
結果の状態 |
|
---|---|
"cur" サブディレクトリ |
"unseen" シーケンス |
"cur" サブディレクトリおよび S フラグ |
"unseen" シーケンス無し |
F フラグ |
"flagged" シーケンス |
R フラグ |
"replied" シーケンス |
When a MaildirMessage
instance is created based upon a
BabylMessage
instance, the following conversions take place:
結果の状態 |
|
---|---|
"cur" サブディレクトリ |
"unseen" ラベル |
"cur" サブディレクトリおよび S フラグ |
"unseen" ラベル無し |
P フラグ |
"forwarded" または "resent" ラベル |
R フラグ |
"answered" ラベル |
T フラグ |
"deleted" ラベル |
mboxMessage
objects¶
- class mailbox.mboxMessage(message=None)¶
mbox 固有の動作をするメッセージ。引数 message は
Message
のコンストラクタと同じ意味を持ちます。mbox メールボックス中のメッセージは単一ファイルにまとめて格納されています。送り主のエンベロープアドレスおよび配送日時は通常メッセージの開始を示す "From " から始まる行に記録されますが、正確なフォーマットに関しては mbox の実装ごとに大きな違いがあります。メッセージの状態を示すフラグ、たとえば読んだかどうかあるいは重要だとマークを付けられているかどうかといったようなもの、は典型的には Status および X-Status に収められます。
規定されている mbox メッセージのフラグは以下の通りです:
Flag
意味
説明
R
読んだもの
読んだもの
O
古い(Old)
以前に MUA に発見された
D
削除(Deleted)
削除予定とされたもの
F
フラグ付き(Flagged)
重要とされたもの
A
返答済み(Answered)
返答されたもの
"R" および "O" フラグは Status ヘッダに記録され、 "D"、"F"、"A" フラグは X-Status ヘッダに記録されます。フラグとヘッダは通常記述された順番に出現します。
mboxMessage
instances offer the following methods:- get_from()¶
mbox メールボックスのメッセージの開始を示す "From " 行を表わす文字列を返します。先頭の "From " および末尾の改行は含まれません。
- set_from(from_, time_=None)¶
Set the "From " line to from_, which should be specified without a leading "From " or trailing newline. For convenience, time_ may be specified and will be formatted appropriately and appended to from_. If time_ is specified, it should be a
time.struct_time
instance, a tuple suitable for passing totime.strftime()
, orTrue
(to usetime.gmtime()
).
- get_flags()¶
現在セットされているフラグを特定する文字列を返します。メッセージが規定された形式に準拠しているならば、結果は次の順に並べられた 0回か1回の
'R'
、'O'
、'D'
、'F'
、'A'
です。
- set_flags(flags)¶
flags で指定されたフラグをセットして、他のフラグは下ろします。flags は並べられたゼロまたは1回の
'R'
、'O'
、'D'
、'F'
、'A'
です。
- add_flag(flag)¶
flag で指定されたフラグをセットしますが他のフラグは変えません。一度に二つ以上のフラグをセットすることは、flag に2文字以上の文字列を指定すればできます。
- remove_flag(flag)¶
flag で指定されたフラグを下ろしますが他のフラグは変えません。一二つ以上のフラグを取り除くことは、flag に2文字以上の文字列を指定すればできます。
When an mboxMessage
instance is created based upon a
MaildirMessage
instance, a "From " line is generated based upon the
MaildirMessage
instance's delivery date, and the following conversions
take place:
結果の状態 |
|
---|---|
R フラグ |
S フラグ |
O フラグ |
"cur" サブディレクトリ |
D フラグ |
T フラグ |
F フラグ |
F フラグ |
A フラグ |
R フラグ |
When an mboxMessage
instance is created based upon an
MHMessage
instance, the following conversions take place:
結果の状態 |
|
---|---|
R フラグおよび O フラグ |
"unseen" シーケンス無し |
O フラグ |
"unseen" シーケンス |
F フラグ |
"flagged" シーケンス |
A フラグ |
"replied" シーケンス |
When an mboxMessage
instance is created based upon a
BabylMessage
instance, the following conversions take place:
結果の状態 |
|
---|---|
R フラグおよび O フラグ |
"unseen" ラベル無し |
O フラグ |
"unseen" ラベル |
D フラグ |
"deleted" ラベル |
A フラグ |
"answered" ラベル |
When a mboxMessage
instance is created based upon an
MMDFMessage
instance, the "From " line is copied and all flags directly correspond:
結果の状態 |
|
---|---|
R フラグ |
R フラグ |
O フラグ |
O フラグ |
D フラグ |
D フラグ |
F フラグ |
F フラグ |
A フラグ |
A フラグ |
MHMessage
objects¶
- class mailbox.MHMessage(message=None)¶
MH 固有の動作をするメッセージ。引数 message は
Message
のコンストラクタと同じ意味を持ちます。MH メッセージは伝統的な意味あいにおいてマークやフラグをサポートしません。しかし、MH メッセージにはシーケンスがあり任意のメッセージを論理的にグループ分けできます。いくつかのメールソフト(標準の mh や nmh はそうではありませんが) は他の形式におけるフラグとほぼ同じようにシーケンスを使います:
シーケンス
説明
unseen
読んではいないが既にMUAに見つけられている
replied
返答されたもの
flagged
重要とされたもの
MHMessage
instances offer the following methods:- get_sequences()¶
このメッセージを含むシーケンスの名前のリストを返す。
- set_sequences(sequences)¶
このメッセージを含むシーケンスのリストをセットする。
- add_sequence(sequence)¶
sequence をこのメッセージを含むシーケンスのリストに追加する。
- remove_sequence(sequence)¶
sequence をこのメッセージを含むシーケンスのリストから除く。
When an MHMessage
instance is created based upon a
MaildirMessage
instance, the following conversions take place:
結果の状態 |
|
---|---|
"unseen" シーケンス |
S フラグ無し |
"replied" シーケンス |
R フラグ |
"flagged" シーケンス |
F フラグ |
When an MHMessage
instance is created based upon an
mboxMessage
or MMDFMessage
instance, the Status
and X-Status headers are omitted and the following conversions
take place:
結果の状態 |
|
---|---|
"unseen" シーケンス |
R フラグ無し |
"replied" シーケンス |
A フラグ |
"flagged" シーケンス |
F フラグ |
When an MHMessage
instance is created based upon a
BabylMessage
instance, the following conversions take place:
結果の状態 |
|
---|---|
"unseen" シーケンス |
"unseen" ラベル |
"replied" シーケンス |
"answered" ラベル |
BabylMessage
objects¶
- class mailbox.BabylMessage(message=None)¶
Babyl 固有の動作をするメッセージ。引数 message は
Message
のコンストラクタと同じ意味を持ちます。ある種のメッセージラベルは アトリビュート と呼ばれ、規約により特別な意味が与えられています。アトリビュートは以下の通りです:
ラベル
説明
unseen
読んではいないが既にMUAに見つけられている
deleted
削除予定とされたもの
filed
他のファイルまたはメールボックスにコピーされた
answered
返答されたもの
forwarded
転送された
edited
ユーザによって変更された
resent
再送された
By default, Rmail displays only visible headers. The
BabylMessage
class, though, uses the original headers because they are more complete. Visible headers may be accessed explicitly if desired.BabylMessage
instances offer the following methods:- get_labels()¶
メッセージに付いているラベルのリストを返します。
- set_labels(labels)¶
メッセージに付いているラベルのリストを labels にセットします。
- add_label(label)¶
メッセージに付いているラベルのリストに label を追加します。
- remove_label(label)¶
メッセージに付いているラベルのリストから label を削除します。
- set_visible(visible)¶
メッセージの可視ヘッダを visible のヘッダと同じにセットします。引数 visible は
Message
インスタンスまたはemail.message.Message
インスタンス、文字列、ファイル風オブジェクト(テキストモードで開かれてなければなりません)のいずれかです。
- update_visible()¶
When a
BabylMessage
instance's original headers are modified, the visible headers are not automatically modified to correspond. This method updates the visible headers as follows: each visible header with a corresponding original header is set to the value of the original header, each visible header without a corresponding original header is removed, and any of Date, From, Reply-To, To, CC, and Subject that are present in the original headers but not the visible headers are added to the visible headers.
When a BabylMessage
instance is created based upon a
MaildirMessage
instance, the following conversions take place:
結果の状態 |
|
---|---|
"unseen" ラベル |
S フラグ無し |
"deleted" ラベル |
T フラグ |
"answered" ラベル |
R フラグ |
"forwarded" ラベル |
P フラグ |
When a BabylMessage
instance is created based upon an
mboxMessage
or MMDFMessage
instance, the Status
and X-Status headers are omitted and the following conversions
take place:
結果の状態 |
|
---|---|
"unseen" ラベル |
R フラグ無し |
"deleted" ラベル |
D フラグ |
"answered" ラベル |
A フラグ |
When a BabylMessage
instance is created based upon an
MHMessage
instance, the following conversions take place:
結果の状態 |
|
---|---|
"unseen" ラベル |
"unseen" シーケンス |
"answered" ラベル |
"replied" シーケンス |
MMDFMessage
objects¶
- class mailbox.MMDFMessage(message=None)¶
MMDF 固有の動作をするメッセージ。引数 message は
Message
のコンストラクタと同じ意味を持ちます。mbox メールボックスのメッセージと同様に、MMDF メッセージは送り主のアドレスと配送日時が最初の "From " で始まる行に記録されています。同様に、メッセージの状態を示すフラグは通常 Status および X-Status ヘッダに収められています。
よく使われる MMDF メッセージのフラグは mbox メッセージのものと同一で以下の通りです:
Flag
意味
説明
R
読んだもの
読んだもの
O
古い(Old)
以前に MUA に発見された
D
削除(Deleted)
削除予定とされたもの
F
フラグ付き(Flagged)
重要とされたもの
A
返答済み(Answered)
返答されたもの
"R" および "O" フラグは Status ヘッダに記録され、 "D"、"F"、"A" フラグは X-Status ヘッダに記録されます。フラグとヘッダは通常記述された順番に出現します。
MMDFMessage
instances offer the following methods, which are identical to those offered bymboxMessage
:- get_from()¶
mbox メールボックスのメッセージの開始を示す "From " 行を表わす文字列を返します。先頭の "From " および末尾の改行は含まれません。
- set_from(from_, time_=None)¶
Set the "From " line to from_, which should be specified without a leading "From " or trailing newline. For convenience, time_ may be specified and will be formatted appropriately and appended to from_. If time_ is specified, it should be a
time.struct_time
instance, a tuple suitable for passing totime.strftime()
, orTrue
(to usetime.gmtime()
).
- get_flags()¶
現在セットされているフラグを特定する文字列を返します。メッセージが規定された形式に準拠しているならば、結果は次の順に並べられた 0回か1回の
'R'
、'O'
、'D'
、'F'
、'A'
です。
- set_flags(flags)¶
flags で指定されたフラグをセットして、他のフラグは下ろします。flags は並べられたゼロまたは1回の
'R'
、'O'
、'D'
、'F'
、'A'
です。
- add_flag(flag)¶
flag で指定されたフラグをセットしますが他のフラグは変えません。一度に二つ以上のフラグをセットすることは、flag に2文字以上の文字列を指定すればできます。
- remove_flag(flag)¶
flag で指定されたフラグを下ろしますが他のフラグは変えません。一二つ以上のフラグを取り除くことは、flag に2文字以上の文字列を指定すればできます。
When an MMDFMessage
instance is created based upon a
MaildirMessage
instance, a "From " line is generated based upon the
MaildirMessage
instance's delivery date, and the following conversions
take place:
結果の状態 |
|
---|---|
R フラグ |
S フラグ |
O フラグ |
"cur" サブディレクトリ |
D フラグ |
T フラグ |
F フラグ |
F フラグ |
A フラグ |
R フラグ |
When an MMDFMessage
instance is created based upon an
MHMessage
instance, the following conversions take place:
結果の状態 |
|
---|---|
R フラグおよび O フラグ |
"unseen" シーケンス無し |
O フラグ |
"unseen" シーケンス |
F フラグ |
"flagged" シーケンス |
A フラグ |
"replied" シーケンス |
When an MMDFMessage
instance is created based upon a
BabylMessage
instance, the following conversions take place:
結果の状態 |
|
---|---|
R フラグおよび O フラグ |
"unseen" ラベル無し |
O フラグ |
"unseen" ラベル |
D フラグ |
"deleted" ラベル |
A フラグ |
"answered" ラベル |
When an MMDFMessage
instance is created based upon an
mboxMessage
instance, the "From " line is copied and all flags directly
correspond:
結果の状態 |
|
---|---|
R フラグ |
R フラグ |
O フラグ |
O フラグ |
D フラグ |
D フラグ |
F フラグ |
F フラグ |
A フラグ |
A フラグ |
例外¶
The following exception classes are defined in the mailbox
module:
- exception mailbox.Error¶
他の全てのモジュール固有の例外の基底クラス。
- exception mailbox.NoSuchMailboxError¶
メールボックスがあると思っていたが見つからなかった場合に送出されます。これはたとえば
Mailbox
のサブクラスを存在しないパスでインスタンス化しようとしたとき(かつ create パラメータはFalse
であった場合)、あるいは存在しないフォルダを開こうとした時などに発生します。
- exception mailbox.NotEmptyError¶
メールボックスが空であることを期待されているときに空でない場合、たとえばメッセージの残っているフォルダを削除しようとした時などに送出されます。
- exception mailbox.ExternalClashError¶
メールボックスに関係したある条件がプログラムの制御を外れてそれ以上作業を続けられなくなった場合、たとえば他のプログラムが既に保持しているロックを取得しようとして失敗したとき、あるいは一意的に生成されたファイル名が既に存在していた場合などに送出されます。
使用例¶
メールボックス中の面白そうなメッセージのサブジェクトを全て印字する簡単な例:
import mailbox
for message in mailbox.mbox('~/mbox'):
subject = message['subject'] # Could possibly be None.
if subject and 'python' in subject.lower():
print(subject)
Babyl メールボックスから MH メールボックスへ全てのメールをコピーし、変換可能な全ての形式固有の情報を変換する:
import mailbox
destination = mailbox.MH('~/Mail')
destination.lock()
for message in mailbox.Babyl('~/RMAIL'):
destination.add(mailbox.MHMessage(message))
destination.flush()
destination.unlock()
この例は幾つかのメーリングリストのメールをソートするものです。他のプログラムと平行して変更を加えることでメールが破損したり、プログラムを中断することでメールを失ったり、はたまた半端なメッセージがメールボックス中にあることで途中で終了してしまう、といったことを避けるように注意深く扱っています:
import mailbox
import email.errors
list_names = ('python-list', 'python-dev', 'python-bugs')
boxes = {name: mailbox.mbox('~/email/%s' % name) for name in list_names}
inbox = mailbox.Maildir('~/Maildir', factory=None)
for key in inbox.iterkeys():
try:
message = inbox[key]
except email.errors.MessageParseError:
continue # The message is malformed. Just leave it.
for name in list_names:
list_id = message['list-id']
if list_id and name in list_id:
# Get mailbox to use
box = boxes[name]
# Write copy to disk before removing original.
# If there's a crash, you might duplicate a message, but
# that's better than losing a message completely.
box.lock()
box.add(message)
box.flush()
box.unlock()
# Remove original message
inbox.lock()
inbox.discard(key)
inbox.flush()
inbox.unlock()
break # Found destination, so stop looking.
for box in boxes.itervalues():
box.close()