【PHP】問い合わせメールフォームを作成する

サンプル

ファイル構成

* 以下のファイルを同階層においておく
+ アプリケーション内部
 + index.html (問い合わせメールフォーム/デザイン部分)
 + sendEmail.php (メール送信)
 + thanks.html
 + error.html

サンプルプログラム

index.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=shift_jis" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<script language="javascript">
function checkData() {
	if (document.getElementById("custmerName").value == "") {
		alert("名前を入力して下さい");
		document.getElementById("custmerName").focus();
		return false;
	} else if (document.getElementById("email").value == "") {
		alert("E-mailを入力して下さい");
		document.getElementById("email").focus();
		return false;
	} else if (!document.getElementById("email").value.match(/.+@.+\..+/)) {
		alert("不正なE-mailが入力されております");
		document.getElementById("email").focus();
		return false;
	} else if (document.getElementById("inquiry").value == "") {
		alert("問い合わせ内容を入力して下さい。");
		document.getElementById("inquiry").focus();
		return false;
	}

	return true;
}
</script>
</head>
<body>
<form id="form" name="form" method="post" action="sendEmail.php">
<p>name *</p><input type="text" name="custmerName" id="custmerName" />
<p>mail address *</p><input type="text" name="email" id="email" />
<p>your inquiry *</p><textarea name="inquiry" id="inquiry" cols="30" rows="20"/></textarea>
<button type="submit" onclick="return checkData()">Send</button>
</form>
</body>
</html>

sendEmail.php

<?php
if ($_POST["custmerName"] == "" || $_POST["email"] == "" || $_POST["inquiry"] == "") {
	header("LOCATION:error.html");
	exit();
}

// 文字化け対策1
mb_language("Japanese");
mb_internal_encoding("SJIS");
mb_detect_order("ASCII, JIS, UTF-8, EUC-JP, SJIS");

// データ取得&文字化け対策2
$custmerName = mb_convert_encoding($_POST["custmerName"], "JIS", "auto");
$custmerMail = mb_convert_encoding($_POST["email"], "JIS", "auto");
$custmerInquiry = mb_convert_encoding($_POST["inquiry"], "JIS", "auto");

// メール作成
$to = "mailaddress@test.com";

$subject = "【件名】";

$body = "\n\n" . $custmerName . "様(メール:$custmerMail)からの問い合わせです。\n\n";
$body = $body . "【お問い合わせ内容】\n\n$custmerInquiry\n\n以上";

$from = "From:$custmerMail";

if (mb_send_mail($to, $subject, $body, $from)) {
	header("LOCATION:thankU.html");
} else {
	header("LOCATION:error.html");
}
?>

thankU.html

<html>
<body>
Thank you!
</body>
</html>

error.html

<html>
<body>
Error... Sorry...
</body>
</html>