我被要求创建一个表单,在提交时向管理员发送一封电子邮件,其中包含整理数据的.csv附件。
我已经浏览了互联网并找到了这个解决方案,它确实有效!但是在提交时我会收到大约3-4封电子邮件(似乎有所不同)。这是代码,还是我已收到垃圾邮件?
HTML表单:
<form method="post">
<p>Enter your email address
<input type="text" name="email" size="50" />
</p>
<p>Please add your first name
<input type="text" name="firstName" size="20" />
</p>
<p>Please add your last name
<input rows="2" name="lastName" size="20"></input>
</p>
<p> </p>
<p> </p>
<p>
<input type="submit" value="Submit" name="B1" />
<input type="reset" value="Reset" name="B2" />
</p>
</form>
PHP代码:
<?php
$email=$_REQUEST['email'];
$firstName=$_REQUEST['firstName'];
$lastName=$_REQUEST['lastName'];
$to = "test@testmail.co.uk";
$subject = "Test subject";
$message = "".
"Email: $email" . "\n" .
"First Name: $firstName" . "\n" .
"Last Name: $lastName";
//The Attachment
$cr = "\n";
$data = "Email" . ',' . "First Name" . ',' . "Last Name" . $cr;
$data .= "$email" . ',' . "$firstName" . ',' . "$lastName" . $cr;
$fp = fopen('diploma_apprenticeship_form_sub.csv','a');
fwrite($fp,$data);
fclose($fp);
$attachments[] = Array(
'data' => $data,
'name' => 'diploma_apprenticeship_form_sub.csv',
'type' => 'application/vnd.ms-excel'
);
//Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//Add the headers for a file attachment
$headers = "MIME-Version: 1.0\n" .
"From: {$from}\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
//Add a multipart boundary above the plain message
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$text . "\n\n";
//Add sttachments
foreach($attachments as $attachment){
$data = chunk_split(base64_encode($attachment['data']));
$name = $attachment['name'];
$type = $attachment['type'];
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" ;
}
$message .= "--{$mime_boundary}--\n";
mail($to, $subject, $message, $headers);
?>
提前致谢,
马特
答案 0 :(得分:0)
最后,我添加了一条if语句,说明电子邮件字段是否等于不发送任何电子邮件。这会阻止在加载页面时触发的电子邮件,以及在提交后页面重置时发送的电子邮件 - 这也是我收到3封电子邮件的原因!