受信したメールから本文を取り出す

提供: とある社畜の頭脳整理
ナビゲーションに移動 検索に移動

メール受信をトリガーにプログラムを起動する」の続きでメール本文を取り出すよ。
僕自身PHPは超初心者だから、他のホームページを参考に作成したよ。
参考元:http://www.phppro.jp/phptips/archives/vol35/1

で、作成したソースがこちら…サンプルソースは本文だけじゃなくて、送信元アドレスや件名も取得しているよ。

#!/usr/local/bin/php
<?php
    require_once '/home/【ドメイン名】/pear/share/pear/Mail/mimeDecode.php';

    // カレントの言語を日本語に設定する
    mb_language("ja");

    // 内部文字エンコードを設定する
    mb_internal_encoding("UTF-8");
    
    // メールデータ取得
    $params['include_bodies'] = true;
    $params['decode_bodies']  = true;
    $params['decode_headers'] = true;
    $params['input'] = file_get_contents("php://stdin");
    $params['crlf'] = "\r\n";
    $structure = Mail_mimeDecode::decode($params);

    //送信者のメールアドレスを抽出
    $mail = $structure->headers['from'];
    $mail = addslashes($mail);
    $mail = str_replace('"','',$mail);

    //署名付きの場合の処理を追加
    preg_match("/<.*>/",$mail,$str);
    if($str[0]!=""){
        $str=substr($str[0],1,strlen($str[0])-2);
        $mail = $str;
    }

    // 件名を取得
    $diary_subject = $structure->headers['subject'];

    switch(strtolower($structure->ctype_primary)){
        case "text": // シングルパート(テキストのみ)
            $diary_body = $structure->body;
            break;
        case "multipart":  // マルチパート(画像付き)
            foreach($structure->parts as $part){
                switch(strtolower($part->ctype_primary)){
                    case "text": // テキスト
                        $diary_body = $part->body;
                        break;
                    case "image": // 画像
                        //画像の拡張子を取得する(小文字に変換
                        $type = strtolower($part->ctype_secondary);
                        //JPEGチェック(GIFやPNG形式の画像チェックなども可
                        if($type != "jpeg" and $type != "jpg"){
                            continue;
                        }
                        
                        //添付内容をファイルに保存
                        $fp = fopen("/tmp/picture.jpg" . $type,"w" );
                        $length = strlen( $part->body );
                        fwrite( $fp, $part->body, $length );
                        fclose( $fp );
                        break;
                }
            }
            break;
            default:
            $diary_body = "";
    }
    /* ここで本文に対する処理をしてね */
?>