本文實例講述了php簡單實現發送帶附件的郵件。分享給大家供大家參考。具體如下:
下面是靜態html代碼:
<html> <head> <title>帶附件的郵件發送</title> </head> <body> <form method="post" name="form1" action="sendmail.php" ENCTYPE="multipart/form-data"> <table> <tr> <td>發送人:</td> <td><input type="text" name="from"></td> </tr> <tr> <td>收件人:</td> <td><input type="text" name="to"></td> </tr> <tr> <td>郵件主題:</td> <td><input type="text" name="subject"></td> </tr> <tr> <td>郵件內容:</td> <td><textarea name="body"></textarea></td> </tr> <tr> <td>附件上傳:</td> <td><input type="file" name="upload_file"></td> </tr> <tr> <td span=2> <input type="submit" value="提交"> <input type="reset" value="重置"> </td> </tr> </table> </form> </body> </html>
sendmail.php文件代碼:
<?php //獲得表單信息 $from = $_POST['from']; $to = $_POST['to']; $subject = $_POST['subject']; $body = $_POST['body']; // 定義分界線 $boundary = "345894369383"; //分界線是一串無規律的字符 //設置header $header = "Content-type: multipart/mixed; boundary= $boundary/r/n"; $header .= "From:$from/r/n"; //獲得上傳文件的文件內容 $file = $_FILES['upload_file']['tmp_name']; //確定上傳文件的MIME類型 $mimeType = $_FILES['upload_file']['type']; //獲得上傳文件的文件名 $fileName = $_FILES['upload_file']['name']; //讀取上傳文件 $fp = fopen($file, "r"); //打開文件 $read = fread($fp, filesize($file)); //讀入文件 $read = base64_encode($read); //base64編碼 $read = chunk_split($read); //切割字符串 //建立郵件的主體,分為郵件內容和附件內容兩部分 $body = "--$boundary Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 8bit $body --$boundary Content-type: $mimeType; name=$fileName Content-disposition: attachment; filename=$fileName Content-transfer-encoding: base64 $read --$boundary--"; //發送郵件 並輸出是否發送成功的信息 if(mail($to, $subject,$body,$header)) { echo "信件發送成功"; } else { echo "信件發送失敗"; } ?>
希望本文所述對大家的php程序設計有所幫助。