Python で IMAP サーバー上のフォルダーを管理する
IMAP フォルダーの一覧表示
Aspose.Email を使用すれば、IMAP サーバーからフォルダー情報を取得するのは簡単です。以下の手順に従ってフォルダーの詳細を取得し、操作してください。
- Aspose.Email の list_folders() メソッドを使用します。 ImapClient クラス。このメソッドはインスタンスを返します。 IMAPフォルダー情報コレクション、すべてのフォルダーに関する詳細が含まれています。
- ループで回す IMAPフォルダー情報コレクション 個々のフォルダー情報にアクセスするオブジェクトです。
- サブフォルダーを取得します(オプション)。list_folders() メソッドはオーバーロードされており、フォルダー名をパラメーターとして渡すことで、指定フォルダーのサブフォルダーのコレクションを取得できます。
以下のコードスニペットは、Aspose.Email のメソッドを使用して IMAP サーバーからフォルダー情報を取得する方法を示しています。
フォルダーの名前変更と削除
Aspose.Email は次のメソッドを提供します。 ImapClient IMAP を介してメールサーバー上のフォルダーを管理するクラス:
- delete_folder メソッド – フォルダーとその中のすべてのメッセージを完全に削除します。
- rename_folder メソッド – フォルダーの内容を変更せずに名前を変更します。
以下のコードスニペットは、IMAP サーバー上のフォルダーをプログラムで削除または名前変更する方法を示しています。
# Delete a folder and Rename a folder
client.delete_folder("foldername")
client.rename_folder("foldername", "newfoldername")
特定のフォルダーにメッセージを作成および追加
Aspose.Email API を使用すると、次のものが利用できます。 MailMessage および ImapClient フォルダーに新しいメッセージを追加するクラスです。まず、 MailMessage 件名、送信者、受信者を指定してオブジェクトを作成します。その後、フォルダーを購読し、メッセージを追加します。以下のコードスニペットは、フォルダーに新しいメッセージを追加する方法を示しています。
- 次のものを使用して IMAP クライアントを初期化します。 ImapClient メールサーバーに接続するクラスです。サーバーアドレス、ポート、ユーザー名、パスワードを指定してください。
- select_folder メソッドを使用して、"Inbox" など新しいメッセージを追加したい対象フォルダーを選択します。
- 次のものを使用して新しいメールを作成します。 MailMessage クラス。送信者、受信者、件名、メッセージ内容を指定します。
- subscribe_folder メソッドでフォルダー名を指定してフォルダーを購読します。
- append_message メソッドを使用して、作成したメッセージを選択したフォルダーに追加します。フォルダー名とメッセージオブジェクトを指定してください。
フォルダー間のメッセージ移動
Aspose.Email for .NET は、次を使用してメッセージをあるメールボックスフォルダーから別のフォルダーへ移動できます。 ImapClient API。move_message メソッドはメッセージのユニーク ID と宛先フォルダー名を使用してメッセージを移動します。以下のコードスニペットは、フォルダー間でメッセージを移動する方法を示しています。
フォルダー間でメッセージをコピー
Aspose.Email API を使用すると、メールボックスのあるフォルダーから別のフォルダーへメッセージを簡単にコピーできます。copy_message および copy_messages メソッドを使用して単一または複数のメッセージをコピーできます。copy_messages メソッドは、ソースフォルダーから宛先フォルダーへ複数のメッセージを転送できます。以下のコードスニペットは、フォルダー間でメッセージをコピーする方法を示しています。
特別用途メールボックスフォルダーの操作
特別用途メールボックスは、送信済み、下書き、迷惑メール、削除済み、アーカイブなど、特定の種類のメッセージを扱うためにメールシステムで事前に定義されたフォルダーです。Aspose.Email ライブラリは、属性を役割や目的に結びつけることで、これらのメールボックスへのアクセスを簡素化します。これにより、ユーザーの介入なしでクライアントが自動的にこれらのフォルダーを検出・表示できます。
以下のコードスニペットは、プロパティを使用して主要な特別用途メールボックス(受信トレイ、下書き、迷惑メール、送信済み、削除済み)の情報を取得する方法を示しています。 ImapMailBoxInfo クラスと詳細を出力します:
import aspose.email as ae
client = ae.clients.imap.ImapClient("imap.domain.com", 993, "user@domain.com", "pwd", ae.clients.SecurityOptions.SSL_IMPLICIT)
mailboxInfo = client.mailbox_info
print(mailboxInfo.inbox)
print(mailboxInfo.draft_messages)
print(mailboxInfo.junk_messages)
print(mailboxInfo.sent_messages)
print(mailboxInfo.trash)
フォルダーにアクセスし、メッセージを再帰的に読み取る
ImapClient 再帰的なメソッドを使用して IMAP サーバーからフォルダーとサブフォルダーを一覧表示します。このメソッドは、メッセージを MSG 形式でローカルディスクに読み込み保存する際にも使用されます。フォルダーとメッセージは、IMAP サーバー上の階層構造と同じ形で作成・保存されます。以下のコードスニペットは、フォルダーとメッセージを再帰的に取得する方法を示しています。
import aspose.email as ae
import os
# Recursive method to get messages from folders and sub-folders
def list_messages_in_folder(folder_info, root_folder, client):
# Create the folder on disk (same name as on the IMAP server)
current_folder = os.path.join(root_folder, folder_info.name)
os.makedirs(current_folder, exist_ok=True)
# Read the messages from the current folder, if it is selectable
if folder_info.selectable:
# Send a status command to get folder info
folder_info_status = client.get_folder_info(folder_info.name)
print(
f"{folder_info_status.name} folder selected. New messages: {folder_info_status.new_message_count}, "
f"Total messages: {folder_info_status.total_message_count}"
)
# Select the current folder and list messages
client.select_folder(folder_info.name)
msg_info_coll = client.list_messages()
print("Listing messages....")
for msg_info in msg_info_coll:
# Get subject and other properties of the message
print("Subject:", msg_info.subject)
print(
f"Read: {msg_info.is_read}, Recent: {msg_info.recent}, Answered: {msg_info.answered}"
)
# Get rid of characters like ? and :, which should not be included in a file name
# Save the message in MSG format
file_name = (
msg_info.subject.replace(":", " ").replace("?", " ")
+ "-"
+ str(msg_info.sequence_number)
+ ".msg"
)
msg = client.fetch_message(msg_info.sequence_number)
msg.save(
os.path.join(current_folder, file_name),
ae.SaveOptions.default_msg_unicode,
)
print("============================\n")
else:
print(f"{folder_info.name} is not selectable.")
try:
# If this folder has sub-folders, call this method recursively to get messages
folder_info_collection = client.list_folders(folder_info.name)
for subfolder_info in folder_info_collection:
list_messages_in_folder(subfolder_info, root_folder, client)
except Exception:
pass
client = ae.clients.imap.ImapClient("imap.domain.com", 993, "user@domain.com", "pwd", ae.clients.SecurityOptions.SSL_IMPLICIT)
try:
# The root folder (which will be created on disk) consists of host and username
root_folder = f"{client.host}-{client.username}"
# Create the root folder and list all the folders from the IMAP server
os.makedirs(root_folder, exist_ok=True)
folder_info_collection = client.list_folders()
for folder_info in folder_info_collection:
# Call the recursive method to read messages and get sub-folders
list_messages_in_folder(folder_info, root_folder, client)
except Exception as ex:
print("\n", ex)
print("\nDownloaded messages recursively from IMAP server.")
バッチフォルダー操作に MultiConnection を使用
Aspose.Email は、クライアントが IMAP サーバーへの複数の同時接続を確立できるようにします。必ずしもパフォーマンスが向上するわけではありませんが、同時操作に対して信頼性のある解決策です。クライアントが複数のメールフォルダーの取得、膨大なデータの同期、複数メッセージの同時処理など、同時に複数のタスクを実行する必要がある場合に特に有用です。
以下のコードスニペットは、‘append_messages’ メソッドを使用してメールメッセージのコレクションをアップロードしながら、IMAP サーバーへの複数接続を確立する方法を示しています。 ImapClient クラス:
import aspose.email as ae
client = ae.clients.imap.ImapClient("imap.domain.com", 993, "user@domain.com", "pwd", ae.clients.SecurityOptions.SSL_IMPLICIT)
client.connections_quantity = 5
client.use_multi_connection = ae.clients.MultiConnectionMode.ENABLE
client.append_messages(messages)