アクアリウムハジメマシタ!!

PHPで添付ファイル付きのメールを送信する「mb_send_mail」編

web@complesso.jp

PHPのメール送信関数mb_send_mailで添付ファイル付きのメールを送信する方法です。

コード例

//言語,エンコード設定
mb_language("ja");
mb_internal_encoding("UTF-8");

//宛先
$to = "test1@example.com";
//送信者
$from = "test2@example.com";
//件名
$subject = "テスト送信です";
//本文
$text = "テスト送信です";

//添付したいファイルのパス
$file_path = "./tmp/test.pdf";
//ファイル名
$file = "test.pdf";

//ヘッダー設定
$header = "Content-Type: multipart/mixed;boundary=\"__BOUNDARY__\"\n";
$header .= "Return-Path: " . $to . " \n";
$header .= "From: " . $from ." \n";
$header .= "Sender: " . $from ." \n";
$header .= "Reply-To: " . $to . " \n";

//本文設定
$body = "--__BOUNDARY__\n";
$body .= "Content-Type: text/plain; charset=\"ISO-2022-JP\"\n\n";
$body .= $text . "\n";
$body .= "--__BOUNDARY__\n";

//添付ファイル設定
$body .= "Content-Type: application/octet-stream; name=\"{$file}\"\n";
$body .= "Content-Disposition: attachment; filename=\"{$file}\"\n";
$body .= "Content-Transfer-Encoding: base64\n";
$body .= "\n";
$body .= chunk_split(base64_encode(file_get_contents($file_path)));
$body .= "--__BOUNDARY__\n";

//送信
mb_send_mail( $to, $subject, $body, $header);

複数の添付ファイルを送信

複数の添付ファイルを送信したい場合は添付ファイル設定の部分を

//一つ目の添付ファイル
$file1 = "test.pdf";
$file_path1 = "./tmp1/test.pdf";

//二つ目の添付ファイル
$file2 = "test.pdf";
$file_path2 = "./tmp2/test.pdf";

//一つ目の添付ファイル設定
$body .= "Content-Type: application/octet-stream; name=\"{$file1}\"\n";
$body .= "Content-Disposition: attachment; filename=\"{$file1}\"\n";
$body .= "Content-Transfer-Encoding: base64\n";
$body .= "\n";
$body .= chunk_split(base64_encode(file_get_contents($file_path1)));
$body .= "--__BOUNDARY__\n";

//二つ目の添付ファイル設定
$body .= "Content-Type: application/octet-stream; name=\"{$file2}\"\n";
$body .= "Content-Disposition: attachment; filename=\"{$file2}\"\n";
$body .= "Content-Transfer-Encoding: base64\n";
$body .= "\n";
$body .= chunk_split(base64_encode(file_get_contents($file_path2)));
$body .= "--__BOUNDARY__\n";

のように変更すれば複数送信できます。