添付ファイルの自動処理
メールの添付ファイルの仕組み
SMTPでメールを送信するとき、DATAコマンドに続いてメールの内容をMIME形式でテキストを送信する。
To:Display Name<[email protected]>\r\n From:\r\n Subject: Content-Type:text/plain \r\n (本文のテキスト)
添付ファイルを含むメールは、本文のテキストを一つのpart、添付ファイルをエンコードしてMIME形式にしたものをもう一つのpartとしたmultipart MIMEとして送信される。
添付ファイルを抽出するには、POPでmultipart MIMEを取得したあと、MIMEをパースしてファイルを取り出せばよい。
Perl
use MIME::IMAPClient;
use Email::MIME;
use Email::MIME::Attachment::Stripper;
use Email::MIME;
use Email::MIME::Attachment::Stripper;
Thunderbird 2.x から送られてくるメールのテキストの添付ファイルは抽出できない。
Content-Type: text/plain; Content-Disposition: inline; filename="...'
なんでもかんでもinline扱い。
とりあえず以下のようにすれば動く。
use Email::MIME::Attachment::Stripper;
{package Email::MIME::Attachment::Stripper;
sub _detach_all {
my ($self, $part) = @_;
$part ||= $self->{message};
return if $part->parts == 1;
my @attach = ();
my @keep = ();
foreach ( $part->parts ) {
my $ct = $_->content_type || 'text/plain';
my $dp = $_->header('Content-Disposition') || 'inline';
push(@keep, $_) and next
if $ct =~ m[text/plain]i && $dp =~ /inline/i && !(defined $_->filename);
push @attach, $_;
if ($_->parts > 1) {
my @kept=$self->_detach_all($_);
push(@keep,@kept) if @kept;
}
}
$part->parts_set(\@keep);
push @{$self->{attach}}, map {
my $content_type = parse_content_type($_->content_type);
{
content_type => join(
'/',
@{$content_type}{qw[discrete composite]}
),
payload => $_->body,
filename => $self->{attr}->{force_filename}
? $_->filename(1)
: ($_->filename || ''),
}
} @attach;
return @keep;
}}