Hatena::ブログ(Diary)

私というひとりの人間。

プロフィール

yespamaster

yespamaster

イエロースパンの中の人

2009-03-07 PHPでメールの添付ファイルの画像を保存する

.forward(メール転送)の設定はよく分からなかったのですが、

以前私の使用しているサーバーに入っているCpanelのメール転送設定で

私のドメインが yellowspan.comだったとしたら、

torikomi@yellowspan.com

が宛先に含まれるときに、

| /usr/local/bin/php /home/hoge/public_html/torikomi.php

する

と設定したら、メールが受信したと同時に torikomi.php が実行されるようになりました。


それ踏まえまして、PHPでメールの添付ファイルの画像を保存する方法です。

PEARの mimeDecode.php を使います。

サーバーに mimeDecode.phpを入れておいて下さい。

torikomi.php



require_once("Mail/mimeDecode.php");

$from="From:" .mb_encode_mimeheader("管理者名") ."<kanri@yellowspan.com>";
$subject = "登録完了しました";
$length = 240;   //最大幅240pxのサムネイル画像を作る

// メールデータ取得 
$input = file_get_contents("php://stdin");
$params['include_bodies'] = true;
$params['decode_bodies']  = true;
$params['decode_headers'] = true; 
$decoder = new Mail_mimeDecode($input, "\r\n");
$structure = $decoder->decode($params);
  
// 送信元アドレス抽出
if (preg_match("/[-!#$%&\'*+\\.\/0-9_`a-z{|}~]+@[-a-z0-9_]+\.[-a-z0-9_\\.]+/i", $structure->headers['from'], $reg)) {
  $to = $reg[0];
}
// 宛先アドレス抽出
if (preg_match("/[-!#$%&\'*+\\.\/0-9_`a-z{|}~]+@[-a-z0-9_]+\.[-a-z0-9_\\.]+/i", $structure->headers['to'], $reg)) {
  $from = $reg[0];
}



$dir = "/home/hoge/public_html/image/";


if(strcasecmp($structure->ctype_primary, 'multipart') == 0){
  foreach($structure->parts as $part){
    if(strcasecmp($part->ctype_primary, 'image') == 0){
      //$filename = $part->d_parameters['filename'];
      $filetype = $part->ctype_secondary;
      $filename = "image.jpg";
      // 画像ファイル自体はファイル保存。
      $image_path = $dir. $filename;
      if($fp = fopen($image_path, 'w')){
        $length = strlen($part->body);
        fwrite($fp, $part->body, $length);
        fclose($fp);
        chmod($image_path, 0644);
        // 画像サイズを縮小
	resizer($image_path);
      }
    }
  }
}
$body =<<<BODY

写真登録完了しました! BODY; mb_send_mail($to,$subject,$body,$from); die; //画像のサイズを縮小する function resizer($filename){ $size=getImageSize($filename); //縦幅より横幅が大きければ横幅を固定、縦幅が大きければ縦幅を固定 if($size[0] >= $size[1]){$width = $length; $high = $size[1] * $length / $size[0];} else{$width = $size[0] * $length / $size[1]; $high = $length;} $img_in=ImageCreateFromJPEG($filename);//元画像を生成 //サイズ変更 $img_out=ImageCreateTruecolor($width,$high); ImageCopyResampled($img_out,$img_in,0,0,0,0,$width,$high,$size[0],$size[1]); ImageJPEG($img_out,$filename);//画像ファイルの書き出し } ?>

画像添付メールを

torikomi@yellowspan.com

に送りましたら、

添付ファイルが

image.jpg

と言う名前で

/home/hoge/public_html/image/

に保存されました。


いかがでしょうか。

フレームワークが必須?

Smartyを使ってます

CakePHPを気にしてます

休みの日に触ってみようかなあ