如何使用PHP表单将图像上传到邮件

时间:2018-12-09 15:42:36

标签: php forms image upload

如何在不使用SMTP或登录特殊电子邮件帐户的情况下通过PHP表单上传发送多个图像?

我的代码仅适用于一个File类型的输入,我想使用4个输入才能显示邮件中的所有4张图像。

当我尝试添加多个文件输入时,会收到“电子邮件发送错误”。

我该怎么办?

这是我的代码:

<form action="sendmail.php" method="post" name="mainform" enctype="multipart/form-data">
<table width="500" border="0" cellpadding="5" cellspacing="5">
      <tr>
  <th>Attach Your File</th>
  <td><input name="attachment" type="file"></td>
</tr>
<tr>
  <th>Attach Your File</th>
  <td><input name="attachment2" type="file"></td>
</tr>
<tr>
  <th>Attach Your File</th>
  <td><input name="attachment3" type="file"></td>
</tr>
<tr>
  <th>Attach Your File</th>
  <td><input name="attachment4" type="file"></td>
</tr>
<tr>
    <td colspan="2" style="text-align:center;"><input type="submit" name="Submit" value="Send"><input type="reset" name="Reset" value="Reset"></td>
</tr>
</table>
</form>


<?php

$to = $_POST['toEmail'];
$fromEmail = $_POST['fieldFormEmail']; 
$fromName = $_POST['fieldFormName']; 
$subject = $_POST['fieldSubject']; 
$message = $_POST['fieldDescription'];

/* GET File Variables */ 
$tmpName = $_FILES['attachment']['tmp_name']; 
$fileType = $_FILES['attachment']['type']; 
$fileName = $_FILES['attachment']['name']; 

/* Start of headers */ 
$headers = "From: $fromName"; 

if (file($tmpName)) { 
  /* Reading file ('rb' = read binary)  */
  $file = fopen($tmpName,'rb'); 
  $data = fread($file,filesize($tmpName)); 
  fclose($file); 

  /* a boundary string */
  $randomVal = md5(time()); 
  $mimeBoundary = "==Multipart_Boundary_x{$randomVal}x"; 

  /* Header for File Attachment */
  $headers .= "\nMIME-Version: 1.0\n"; 
  $headers .= "Content-Type: multipart/mixed;\n" ;
  $headers .= " boundary=\"{$mimeBoundary}\""; 

  /* Multipart Boundary above message */
  $message = "This is a multi-part message in MIME format.\n\n" . 
  "--{$mimeBoundary}\n" . 
  "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . 
  "Content-Transfer-Encoding: 7bit\n\n" . 
  $message . "\n\n"; 

  /* Encoding file data */
  $data = chunk_split(base64_encode($data)); 

  /* Adding attchment-file to message*/
  $message .= "--{$mimeBoundary}\n" . 
  "Content-Type: {$fileType};\n" . 
  " name=\"{$fileName}\"\n" .
  "Content-Transfer-Encoding: base64\n\n" . 
  $data . "\n\n" . 
  "--{$mimeBoundary}--\n"; 
} 

$flgchk = mail ("$to", "$subject", "$message", "$headers"); 

if($flgchk){
  echo "A email has been sent to: $to";
 }
else{
  echo "Error in Email sending";
}
?>

1 个答案:

答案 0 :(得分:-1)

发布大量代码并要求对其进行分析并不是很好。 ;-)

通常:尝试将要发送的数据流写入文件,然后对其进行分析-手动或使用某种邮件工具(甚至可能是发出警告的邮件客户端)。尝试手动构造带有多个附件的有效电子邮件,然后尝试使用您的代码重现该格式。

在您的情况下:我看到一个与“具有多个文件的问题”不直接相关的问题,但是与内容类型有关的一个问题(因此,我不是写评论,而是一个答案):charset iso- 8859-1 不应与“ 7bit ”一起使用,而应与“ 8bit”或“ quoted-printable”编码一起使用。

EDIT1:修正不良英语。

EDIT2:再次阅读您的代码。我看不到\ r代表CRLF行尾。