#!/usr/bin/perl use Getopt::Std ; use File::Basename ; use MIME::Parser ; use MIME::Lite ; use Jcode ; # コマンドライン引数 my %opt ; getopts( "t:" , \%opt ) ; # メールの解析 my $parser = MIME::Parser->new ; #ファイルの一時保存場所を指定 $parser->output_dir('/tmp') ; #標準入力からメールを取得 my $entity = $parser->parse(*STDIN) ; #FromとSubjectのみ取り出し my $from = $entity->head->get('From') ; my $subject = $entity->head->get('Subject') ; # 前後空白のトリミング $from =~ s/^\s+// ; $from =~ s/\s+$// ; $subject =~ s/^\s+// ; $subject =~ s/\s+$// ; # 変換後の添付ファイルの初期化 my $msg = MIME::Lite->new( From => $from , To => $opt{'t'} , Subject => $subject , Type => 'multipart/mixed' , ) ; #添付ファイルがある場合のみ処理 if( $entity->is_multipart ) { my $count = 0 ; #メール本文以外(添付のみ)を取り出し for( $i = 0 ; $i < $entity->parts ; $i++ ) { #ファイル名を含むパスを取り出し $path = $entity->parts($i)->bodyhandle->path ; #ファイル名を取り出し $filename = (fileparse($path))[ 0 ] ; if ( $path =~ /\.txt$/ ) { # テキストファイルを読む my $text = "" ; open( FH , $path ) or die( "Can't read $path" ) ; while( ) { $text .= $_ ; } close( FH ) ; # テキストを添付 $msg->attach( Type => 'text/plain; charset="iso-2022-jp"' , Encoding =>'7bit' , Data => jcode( $text )->jis ) ; $count++ ; } elsif ( $path =~ /^[\/\.\w-]+\.3gp$/ ) { # 音声ファイルの形式を変換 system( "/usr/bin/avconv -v quiet" ." -i $path -ar 22050 -f wav $path.mp3" ) ; # 音声ファイルを添付 $msg->attach( Type => 'audio/3gpp' , Path => "$path.mp3" , Filename => "$filename.mp3" , Disposition => 'attachment' ) ; $count++ ; } } if ( $count > 0 ) { # 新しい添付メールを送信 $msg->send ; } # 取り出された添付ファイルを消す for( $i = 0 ; $i < $entity->parts ; $i++ ) { $path = $entity->parts($i)->bodyhandle->path ; unlink( $path ) ; if ( $path =~ /^[\/\.\w-]+\.3gp$/ ) { unlink( "$path.mp3" ) ; } } } else { # ただのテキストファイルの場合 open( FH , "| /usr/sbin/sendmail -t" ) or die( "Can't open sendmail" ) ; print FH "From: $from\n" ."To: ".$opt{'t'}."\n" ."Subject: $subject\n" ."\n" ; foreach my $line ( @{$entity->body} ) { print FH $line ; } close( FH ) ; }