- PHP
- 2020-10-19 - 更新:2020-11-16
PHPのmb_send_mail関数でファイルを添付してメールを送信するスクリプト
$to = "mailto@example.jp"; $from = "mailfrom@example.jp"; $subject = "件名"; $mailbody = "メール本文\n"; $boundary = md5(uniqid(rand())); //バウンダリー文字(パートの境界) $header = "From: $to\n" . "Reply-To: $from\n" . "X-Mailer: PHP/".phpversion()."\n" . "MIME-version: 1.0\n" . "Content-Type: multipart/mixed;\n" . "\tboundary=\"$boundary\"\n"; $msg = "This is a multi-part message in MIME format.\n\n" . "--$boundary\n" . "Content-Type: text/plain; charset=iso-2022-jp\n" . "Content-Transfer-Encoding: 7bit\n\n" . $mailbody."\n" . "\n"; // 画像(upfileという名前でアップロードされたとする) if($_FILES["upfile"]["error"] == UPLOAD_ERR_OK) { $tmp = $_FILES["upfile"]["tmp_name"]; $name = $_FILES["upfile"]["name"]; $size = $_FILES["upfile"]["size"]; $array = explode(".", $name); $nr = @count($array); $ext = $array[$nr - 1]; $name = date("U").".".$ext; $fp = fopen($tmp, "r"); $contents = fread($fp, filesize($tmp)); fclose($fp); $f_encoded = chunk_split(base64_encode($contents)); //エンコード $msg .= "--$boundary\n" . "Content-Type: application/octet-stream;\n" . "\tname=\"$name\"\n" . "Content-Transfer-Encoding: base64\n" . "Content-Disposition: attachment;\n" . "\tfilename=\"$name\"\n\n" . "$f_encoded\n" . "\n"; } //[end if] // language establish mb_language("ja"); // original encoding $orgEncoding = mb_internal_encoding(); // specify internal encoding mb_internal_encoding("utf-8") ; //メール送信 if(!mb_send_mail($mailto, $subject, $msg, $header)) { echo "メールの送信に失敗しました。"; } // internal encoding take back mb_internal_encoding($orgEncoding);