WatchOS5 を使うと、メール添付画像を見ることができるので、監視システムなどから画像付きでメールを送りたくなった。HTML形式で画像へのリンクを送っても画像はみえない。
#!/usr/bin/perl
=head1 使用方法
mail-mixed.jp [options] 宛先... 標準入力をメール本文として送る
-t --to 宛先
-c --cc CC宛先
-b --bcc BCC宛先
-f --from 差し出し人
-s --subject タイトル
-a --attach 添付
-h --html HTML形式かどうか
=cut
use warnings ;
use Getopt::Long ;
use Jcode ;
use Encode ;
use utf8 ;
use MIME::Lite ;
use File::MimeInfo::Magic ;
my $m_from = "" ;
my $m_html = 0 ;
my @m_attach = () ;
my @m_to = () ;
my @m_cc = () ;
my @m_bcc = () ;
my $m_body = "" ;
# オプションの読み込み
GetOptions( 'to=s' => \@m_to , 'cc=s' => \@m_cc , 'bcc=s' => \@m_bcc ,
'from=s' => \$m_from ,
'subject=s' => \$m_subject ,
'attach=s' => \@m_attach ,
'html' => \$m_html ,
) ;
# 残りのオプション To として扱う
@m_to = ( @m_to , @ARGV ) ;
# 標準入力はメール本文
while( ) {
$m_body .= $_ ;
}
# メール MIME::Lite用引数
my %arg = () ;
$arg{From} = $m_from ;
if ( $m_html ) {
# $arg{Subject} = encode( 'MIME-Header' , $m_subject ) ;
# UTF-8だと文字化けするぞ
# $arg{Subject} = encode( 'MIME-Header-UTF_8' , Jcode->new( $m_subject )->utf8 ) ;
$arg{Subject} = encode( 'MIME-Header-ISO_2022_JP' , Jcode->new( $m_subject )->jis ) ;
} else {
$arg{Subject} = encode( 'MIME-Header-ISO_2022_JP' , Jcode->new( $m_subject )->jis ) ;
}
$arg{To} = join( ", " , @m_to ) if ( @m_to > 0 ) ;
$arg{Cc} = join( ", " , @m_cc ) if ( @m_cc > 0 ) ;
$arg{Bcc} = join( ", " , @m_bcc ) if ( @m_bcc > 0 ) ;
$arg{Type} = 'multipart/mixed' ;
# メール全体の作成
my $msg = MIME::Lite->new( %arg ) ;
# メール本文の作成
if ( $m_html ) {
# HTML形式ではUTF-8を使う
$msg->attach(
Type => 'text/html; charset="utf-8"' ,
Data => Jcode->new( $m_body )->utf8 ) ;
} else {
# それ以外は日本語ISO-2022-JP
$msg->attach(
Type => 'text/plain; charset="iso-2022-jp"' ,
Encoding => '7bit' ,
Data => Jcode->new( $m_body )->jis ) ;
}
# 添付ファイルを付ける
foreach my $file ( @m_attach ) {
if ( -r $file ) {
my $r_file = $file ;
# ファイル名のディレクトリ部を削除
$r_file =~ s/^.*\/// ;
# 添付
$msg->attach(
Type => mimetype( $file ) ,
Path => $file ,
Filename => $r_file ,
Disposition => 'attachment' ) ;
}
}
# メールを送る
$msg->send ;
### Local Variables: ###
### mode: perl ###
### End: ###