[PHP]今や当たり前のComposerをLinuxにインストールしてphp-mime-mail-parserを使う

こんにちは。

先日、PEAR/Mail_MimeDecodeを使ったメール解析をエントリーしました。

[Linux]メールを受信したらPHPで自動返信メールを送信する
こんにちは。 BIG1等を当てたいサラリーマンです。 aliases(エイリアス)を使ってメール受信をトリガーにPHPを実行する方法...

今回は、Composerを利用して、メール解析にphp-mime-mail-parserを導入しました。
手順と、使用感などを記事にまとめました。

目次

Composerの導入

Composerとは

パッケージ管理ツールです。
プロジェクト単位でパッケージを管理できるのが特徴です。

インストール

composer.pharをダウンロードします。

cd
curl -sS https://getcomposer.org/installer | php

オプション-sは、ダウンロードの進捗とエラーメッセージを表示しない。
-sと-Sを、併用するとエラーメッセージだけは表示する。

プログラムをパスが通ったディレクトリに移動します。

sudo -s mv composer.phar /usr/local/bin/

ライブラリ(php-mime-mail-parser)の追加

Composerに対応しているライブラリやJSONの記述方法、必要条件などはPackgistで検索して確認できます。

Packagist

ライブラリの確認

php-mime-mail-parserを検索します。
最新バージョンは2.1.2、PHP5.4以上とext-mailparseが必要なようです。

SS 2015-09-15 5.12.58

JSONファイル配置

example.comの直下に移動します。

cd /var/www/html/example.com

ファイル名composer.json、以下の内容で作成します。

{
    "require": {
        "php-mime-mail-parser/php-mime-mail-parser": "2.1.2"
    }
}

インストール

composer.phar install

以上が、基本的なインストールと使い方ですが、php-mime-mail-parserは依存パッケージが必要なようで以下のメッセージが表示されました。

  Problem 1
    - Installation request for php-mime-mail-parser/php-mime-mail-parser 2.1.2 -> satisfiable by php-mime-mail-parser/php-mime-mail-parser[2.1.2].
    - php-mime-mail-parser/php-mime-mail-parser 2.1.2 requires ext-mailparse * -> the requested PHP extension mailparse is missing from your system.

やはり、ext-mailparseのインストールが必要のようです。
PHPドキュメントによるとMailparseモジュールは、PECLレポジトリで提供されているようです。

PHP: 導入 – Manual

PECL導入

PECLとは

Wikipediaから抜粋しました。

PECL(ピクル、PHP Extension Community Library)は、PHPで利用できる拡張ライブラリ(パッケージ)を提供しているサービス。

PECLで提供されるライブラリはCで記述されているため、PHPで記述されたPEARのライブラリよりも高速に動作する。PECLにより提供されるライブラリはPHPの拡張モジュールとしてインストールされる。一方で、PEARライブラリはPHPのバージョンアップに伴う再インストールが原則として不要なのに対し、PECL拡張モジュールはPHP内部のAPIに依存する部分があるため、PHPのバージョンアップに伴いAPIが変更された場合は再コンパイルを必要とする。

SS 2015-09-15 5.26.42

インストールはPEARから行い、Cのコンパイラも必要とのことです。

PEARをインストール

sudo yum --enablerepo=remi-php56 install -y php-pear
sudo yum --enablerepo=remi --enablerepo=remi-php56 install -y php-pear

必要なパッケージをインストール

sudo yum -y install httpd-devel
sudo yum -y install gcc gcc-c++

mailparseインストール

sudo yum --enablerepo=remi-php56 install -y php-pecl-mailparse
sudo yum --enablerepo=remi --enablerepo=remi-php56 install -y php-pecl-mailparse

Mailparseがインストール出来たので、再度composer.phar installを実行します。

Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing php-mime-mail-parser/php-mime-mail-parser (2.1.2)
    Downloading: 100%         

Writing lock file
Generating autoload files

インストール出来ました。

メール解析

ソース(PHPファイル)を配置

Packagistのphp-mime-mail-parserページで公開されていたソースを少し編集して次のようにしました。

<?php
//We need to add the library first !
require_once __DIR__.'/vendor/autoload.php';

// $path = 'path/to/mail.txt';
$Parser = new PhpMimeMailParser\Parser();
$raw_mail = stream_get_contents(STDIN);
$Parser->setText($raw_mail);

//There are three input methods of the mime mail to be parsed
//specify a file path to the mime mail :
// $Parser->setPath($path); 

// Or specify a php file resource (stream) to the mime mail :
// $Parser->setStream(fopen($path, "r"));

// Or specify the raw mime mail text :
// $Parser->setText(file_get_contents($path));

// We can get all the necessary data
// $to = $Parser->getHeader('to');
$from = $Parser->getHeader('from');
$subject = $Parser->getHeader('subject');

$text = $Parser->getMessageBody('text');
$html = $Parser->getMessageBody('html');
$htmlEmbedded = $Parser->getMessageBody('htmlEmbedded'); //HTML Body included data

// and the attachments also
$attach_dir = '/var/www/html/example.com/attachments/';
$Parser->saveAttachments($attach_dir);

// loop the attachments
$attachments = $Parser->getAttachments();
if (count($attachments) > 0) {
    foreach ($attachments as $attachment) {
        echo 'Filename : '.$attachment->getFilename().'<br />'; // logo.jpg
        echo 'Filesize : '.filesize($attach_dir.$attachment->getFilename()).'<br />'; // 1000
        echo 'Filetype : '.$attachment->getContentType().'<br />'; // image/jpeg
    }
}

// Write Text
$log = "From : {$from}\nSubject : {$subject}\nText : {$text}\nHTML : {$html}\nEmbedded : {$htmlEmbedded}\n";
$fp = fopen('/var/www/html/example.com/mailphp.log', 'a');
fwrite($fp, $log);
fclose($fp);

解析内容をログファイルに書き出し、添付フィアルをディレクトリに保存します。

ファイル名をexecmail.phpとし、example.comの直下に配置します。
添付ファイルの保存ディレクトリのattachmentsを、同じくexample.comの直下に作成します。

aliases設定

こちらのエントリーで設定した、aliasesを使ってexecmail.phpを実行します。

[Linux]メールを受信したらPHPで自動返信メールを送信する
こんにちは。 BIG1等を当てたいサラリーマンです。 aliases(エイリアス)を使ってメール受信をトリガーにPHPを実行する方法...

テストメール送信

次のメールを作成して送信しました。
SS 2015-09-11 5.45.05

まとめ

Composerは簡単に導入できました。
Mail_MimeDecodeとphp-mime-mail-parserを比較すると導入は、Mail_MimeDecodeの方が簡単でした。
しかし、Composerを使ったパッケージ管理の方がプロジェクト毎に使いたいパッケージ(ライブラリ)を追加できるので複数のパッケージを多用する場合は良いと思いました。

メール解析は、Mail_MimeDecodeに比べて、php-mime-mail-parserの方が扱いやすく感じました。
必要な要素の取り出し、添付ファイルの保存、ソースの可読性も良いと思います。

参考ページ

Composerを使ってPHPのパッケージを簡単インストール

ケーワン・エンタープライズのエンジニアメモ(`・ω・´)ゞビシッ!!: PHP(と拡張ライブラリ)のインストール

スポンサーリンク
レクタングル(大)
レクタングル(大)

コメントをどうぞ

メールアドレスが公開されることはありません。

CAPTCHA


次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>