Open Source Web Development Tutorials - Dev Shed
PHPでメール送信機能を実装しよう
(2009/02/26公開)
コードの解説
コードを見ていきましょう。まず最初に、フォームが提出されたことを確認します。
<?
//is form submitted
if(isset($_POST['key'])){
そして、フォームのデータを収集し、短い変数に格納します。
//collect the information
$from=$email;
$cc=$_POST['cc'];
$bcc=$_POST['bcc'];
次に、データのフィルター処理を行い、各必須フィールドのエラーメッセージを設定します。
if(empty($_POST['tos'])){
$error=true;
}else{
$to=$_POST['tos'];
}
if(empty($_POST['sub'])){
$error=true;
}else{
$subject=$_POST['sub'];
}
if(empty($_POST['msg'])){
$error=true;
}else{
$msg=$_POST['msg'];
}
最後に、添付ファイルの有無を検証します。添付ファイルは配列$_FILES['']によって送信します。ファイルをロードする場合は、mail関数のヘッダーを設定します。content-dispositionおよびcontent-transfer-encodingも設定している点に、注意してください。
//check if the an attachment is present
if(isset($_FILES['userfile']['name'])){
$attachment = $_FILES['userfile']['tmp_name'], $_FILES['userfile']['name'];
$headers ="Content-disposition: attachment;
$filename=.$attachment."n";
$headers=.Content-Transfer-Encoding: base64n";
}
エラーが存在しなければ、ヘッダーの有無に拘わらず、メールメッセージを送信します。
if(!$error){
if($headers <> ""){
$res=mail($to,$subject,$msg,$headers);
}else{
$res=mail($to,$subject,$msg);
}
}
最後に、ユーザーに通知するエラーの有無を確認します。
if(!$res){
echo "Mail error occurred";
}
}
?>
Copyright © 2008 Ziff Davis Enterprise, Inc.
Originally appearing in the U.S. Edition of Dev Shed. All Rights Reserved.








