📢 Webサイト閉鎖と移転のお知らせ
このWebサイトは2026年9月に閉鎖いたします。
新しい記事は移転先で追加しております。(旧サイトでは記事を追加しておりません)

 
198行目: 198行目:
<br>
<br>
  <syntaxhighlight lang="php">
  <syntaxhighlight lang="php">
  $mailbox = new PhpImap\Mailbox(
  <?php
    '{imap.example.com:993/imap/ssl}INBOX',
// Composerで使用されるPHPのパッケージ管理システムに関連する重要な記述
    '<ユーザ名>',
// 必要なクラスファイルを自動的にrequire/includeする
    '<パスワード>'
require 'vendor/autoload.php';
);
   
   
  $emails = $mailbox->searchMailbox('ALL');
  use PhpImap\Mailbox;
use PhpImap\Exceptions\ConnectionException;
use PhpImap\Exceptions\InvalidParameterException;
/*
  * メール処理を行うクラス
  */
class MailProcessor
{
    private $mailbox;
    private $server;
    private $username;
    private $password;
    /**
    * コンストラクタ
    *
    * @param string $server IMAPサーバーアドレス (例: imap.example.com)
    * @param string $username ユーザー名
    * @param string $password パスワード
    */
    public function __construct(string $server, string $username, string $password)
    {
      $this->server = $server;
      $this->username = $username;
      $this->password = $password;
    }
    /**
    * メールボックスへの接続を確立
    *
    * @throws ConnectionException 接続エラー時
    * @return bool 接続成功時にtrue
    */
    public function connect(): bool
    {
      try {
          // IMAPサーバへの接続文字列を構築
          $imapPath = sprintf('{%s:993/imap/ssl}INBOX', $this->server);
          // メールボックスオブジェクトを初期化
          $this->mailbox = new Mailbox($imapPath, $this->username, $this->password,
                                      __DIR__ . '/attachments', // 添付ファイル保存ディレクトリ
                                      'UTF-8'                  // 文字エンコーディング
          );
          // 接続
          $this->mailbox->checkMailbox();
          return true;
      }
      catch (ConnectionException $e) {
          throw new ConnectionException('メールサーバーへの接続に失敗しました: ' . $e->getMessage());
      }
    }
    /**
    * メールを検索して取得
    *
    * @param string $criteria 検索条件 (例: 'ALL', 'UNSEEN', 'FROM "someone@example.com"')
    * @return array 検索結果のメール情報配列
    */
    public function searchMails(string $criteria = 'ALL'): array
    {
      try {
          // メールを検索
          $mailsIds = $this->mailbox->searchMailbox($criteria);
          $results = [];
          foreach ($mailsIds as $mailId) {
            try {
                $email = $this->mailbox->getMail($mailId);
                $results[] = [
                        'id' => $mailId,
                        'subject' => $email->subject,
                        'from' => $email->fromAddress,
                        'date' => $email->date,
                        'body' => $email->textPlain,
                        'hasAttachments' => $email->hasAttachments()
                ];
            }
            catch (\Exception $e) {
                // 個別のメール取得エラーをログに記録し、処理を継続
                error_log("メールID {$mailId} の取得に失敗: " . $e->getMessage());
                continue;
            }
          }
          return $results;
      }
      catch (InvalidParameterException $e) {
          throw new InvalidParameterException('無効な検索条件が指定されました: ' . $e->getMessage());
      }
    }
    /**
    * メールボックスの接続を終了
    */
    public function disconnect(): void
    {
      if ($this->mailbox) $this->mailbox->disconnect();
    }
}
</syntaxhighlight>
<br>
<syntaxhighlight lang="php">
// 使用例
try {
    // メールプロセッサのインスタンスを生成
    $processor = new MailProcessor(
        'imap.example.com',
        '<ユーザー名>',
        '<パスワード>'
    );
    // 接続
    $processor->connect();
    // 未読メールを検索
    $unreadMails = $processor->searchMails('UNSEEN');
    // 結果を処理
    foreach ($unreadMails as $mail) {
      echo "Subject: " . $mail['subject'] . "\n";
      echo "From: " . $mail['from'] . "\n";
      echo "Date: " . $mail['date'] . "\n";
    }
}
catch (ConnectionException $e) {
    // 接続エラーの処理
    error_log("接続エラー: " . $e->getMessage());
    exit(1);
}
catch (InvalidParameterException $e) {
    // パラメータエラーの処理
    error_log("パラメータエラー: " . $e->getMessage());
    exit(1);
}
catch (\Exception $e) {
    // その他の予期せぬエラーの処理
    error_log("予期せぬエラー: " . $e->getMessage());
    exit(1);
}
finally {
    // 確実に接続を終了
    if (isset($processor)) {
        $processor->disconnect();
    }
}
  </syntaxhighlight>
  </syntaxhighlight>
<br>
<br>
==== 推奨されるアプローチ ====
==== 推奨されるアプローチ ====
新規システムを設計する場合は、以下に示す順序で検討することが推奨される。<br>
新規システムを設計する場合は、以下に示す順序で検討することが推奨される。<br>