2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UTF8の記号入り文章をHTMLメールで送るperlスクリプト

Last updated at Posted at 2015-03-11

perlでメールを送る時に記号が入ってると文字化けしちゃうのでHTMLメールで送ることにしました。

送るテキストファイル(mail.txt)、文字コードUTF8です。

普通の日本語です。
☀☁☂☃☎☏☚☛☜☝☞☟
☠☢☣☤☥☪☭☯☹☺☻☼☽☾
♔♕♖♘♚♛♞♠♡♢♣♤♥♦♧
♨♩♪♫♬♭♮♯✂✄✈✍✎✏✐
✑✓✘✳❀➘➙➚➜➥➦➷➸➹
普通の日本語です。

プログラム

html_mail.pl
# !/usr/bin/perl

use utf8;
use strict;
use Encode;
use Encode::MIME::Header;

my $subject = 'UTF8の記号を送るよ!';
my $to_mail = 'address@example.com';

my $mime_subject = encode( 'MIME-Header-ISO_2022_JP', $subject );
my $mime_to_mail = encode( 'MIME-Header-ISO_2022_JP', $to_mail );

my $body = '';
for (<>) {
	my $utf8 = decode_utf8($_);
	$body .= encode( 'jis', $utf8, Encode::FB_HTMLCREF );
}

my $mail_cmd = '/usr/sbin/sendmail';

my $header = '';
$header .= "MIME-Version: 1.0\n";
$header .= "To: " . $mime_to_mail . "\n";
$header .= "Subject: " . $mime_subject . "\n";
$header .= "Content-type: text/html; charset=ISO-2022-JP\n";
$header .= "Content-Transfer-Encoding: 7bit\n";
$header .= "\n";

if ( open( SMAIL, "| $mail_cmd -t -i" ) ) {
	print SMAIL $header;
	print SMAIL '<html><body><pre>' . "\n";
	print SMAIL $body . "\n";
	print SMAIL '</pre></body></html>' . "\n";
	close(SMAIL);
}
else {
	print STDERR "ERROR $!\n";
}

exit(0);

1;

実行

./html_mail.pl < mail.txt

結果

記号入りでメールが届きました。

普通の日本語です。
☀☁☂☃☎☏☚☛☜☝☞☟
☠☢☣☤☥☪☭☯☹☺☻☼☽☾
♔♕♖♘♚♛♞♠♡♢♣♤♥♦♧
♨♩♪♫♬♭♮♯✂✄✈✍✎✏✐
✑✓✘✳❀➘➙➚➜➥➦➷➸➹
普通の日本語です。

ポイント

JISにエンコードする時の Encode::FB_HTMLCREF 部分が重要です。これがないと文字化けして届きました。

普通の日本語です。
????????????
??????????????
???????????????
??♪??♭?♯???????
??????????????
普通の日本語です。

参考サイト

@dankogaiさんの記事を参考にさせていただきました。

404 Blog Not Found : perl - Encode 中級

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?