この記事には広告を含む場合があります。
記事内で紹介する商品を購入することで、当サイトに売り上げの一部が還元されることがあります。
PHPでメールデータを解析する
メール情報を PHP で解析するためプログラムを記載します。今回は PHP ライブラリである PEAR の「Mail/mimeDecode.php」を利用します。
解析するための前準備
もしサーバーに該当のモジュールがインストールされいない場合は、PEARのメールモジュールをインストールします。
yum install php-pear-Mail yum install php-pear-Mail-mimeDecode
※CentOS の場合は上記のコマンドで必要なモジュールをインストールすることができます。
プログラム
構成は同じ階層に
- CtrlMail.php
- analysis.php
- mail.txt
を配置したものとします。
メールデータは昨日のブログ「メールデータの構造」で記載したメールデータを利用します。
CtrlMail.php
<?php
//PEAR の Mail/mimeDecode.php を読み込む
require_once 'Mail/mimeDecode.php';
class CtrlMail
{
/**
* メールデータを解析する
* @param $mailTxt メールデータ
* @return メールの解析結果
*/
function analytics($mailTxt) {
$params = [];
$params['include_bodies'] = true; //返却されるデータにメール本体を含むかどうか
$params['decode_bodies'] = true; //返却されるデータのメール本体をデコードするかどうか
$params['decode_headers'] = true; //返却されるデータのメールヘッダーをデコードするかどうか
$params['crlf'] = "\r\n"; //改行コードの指定
//メール本文を設定
$params['input'] = $mailTxt;
//メールを解析したときにエラーの場合はnullを返却する
$mailList = null;
try{
$mailList = Mail_mimeDecode::decode($params);
}catch(Exception $e) {
$mailList = null;
}
return $mailList;
}
}
analysis.php
<?php
require_once dirname(__FILE__) . '/CtrlMail.php';
$ctrlMail = new CtrlMail();
var_dump($ctrlMail->analytics(file_get_contents('mail.txt')));
実行結果
object(stdClass)#3 (5) {
["headers"]=>
array(9) {
["delivered-to"]=>
string(19) "receive@example.com"
["return-path"]=>
string(24) "<send@example.com>"
[""]=>
string(28) "ヘッダー情報を中略)"
["content-type"]=>
string(40) "text/plain; charset=UTF-8; format=flowed"
["content-transfer-encoding"]=>
string(4) "8bit"
["date"]=>
string(31) "Tue, 12 Jul 2018 14:00:00 +0900"
["from"]=>
string(16) "send@example.com"
["to"]=>
string(19) "receive@example.com"
["subject"]=>
string(18) "テストメール"
}
["ctype_primary"]=>
string(4) "text"
["ctype_secondary"]=>
string(5) "plain"
["ctype_parameters"]=>
array(2) {
["charset"]=>
string(5) "UTF-8"
["format"]=>
string(6) "flowed"
}
["body"]=>
string(92) "テストメールです。
あいうえお
かきくけこ
さしすせそ
たちつてと
"
}
ウェブプログラミングについては下記の本も参考になるので、スキルアップにお役立てください。


