11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[PHP] 外部のメールサーバーに IMAP で接続してメールの送信内容をテストする

Posted at

PHP に IMAP サーバーに接続して受信したメール内容を取得できる imap 系の関数が用意されていることを知りました。この機能はエンドツーエンドテストに利用できそうです。

実際に送信したメールの内容をテストしているため、途中で sleep をして受信されるのを待っています。テストの方法としてはベストではないかもしれませんが、取り急ぎテストで保護したい場合に使えるのではないかと思います。

以下のテストコードは Gmail のメールサーバーに接続して、一番新しいメッセージの本文が期待したものになっているかどうかを確かめています。

EmailTest.php
<?php

class EmailTest extends PHPUnit_Framework_TestCase{

  public function setUp(){
    mb_language('ja');
    mb_internal_encoding('UTF-8');
    $this->hostname = 'imap.googlemail.com';
    $this->port = '993';
    $this->flags = '/novalidate-cert/imap/ssl';
    $this->username = 'your_username';
    $this->password = 'your_password';
    $this->to = 'your_username@example.com';
  }

  public function testEmail(){
    mb_send_mail($this->to, 'test subject', 'test body');
    sleep(5);
    $mbox = imap_open(
      '{' . $this->hostname . ':' . $this->port . $this->flags . '}INBOX',
      $this->username,
      $this->password
    );  
    $count = imap_num_msg($mbox);
    $actual = mb_convert_encoding(imap_body($mbox, $count), 'UTF-8', 'AUTO');
    imap_close($mbox);
    $expected = 'test body' . "\r\n";
    $this->assertEquals($expected, $actual);
  }
}

上記のテストの手順を日本語で書くと下記となります。

  1. imap_open 関数で IMAP サーバーに接続します。
  2. imap_num_msg 関数でメールサーバーに保存されているメッセージの数を取得します。
  3. imap_body 関数でメッセージの本文を取得します。取得したいメッセージの番号を第二引数に渡します。今回試した限りでは、古いメッセージから順番に番号がふられており、最も新しいメッセージの番号はサーバーに保存されているメッセージの数と同じ値になりました。なので、手順 2 でサーバーに保存されているメッセージの数を取得しています。
  4. 取得した本文と期待された値が一致しているか確かめます。

下記を参考にしました。ありがとうございます。
http://d.hatena.ne.jp/oniloq/20121129/1354122428

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?