我写这篇文章是因为,在我们的日常编程中,我们做我们想与每个人分享的事情,以便通过互相帮助使编程更简单。

最近,我处理一项任务,我需要从窗体生成 CSV 文件,然后通过电子邮件发送该文件。我们还可以使用下面的方法将数据库生成的数据 CSV 文件通过电子邮件发送到电子邮件中。

让我们首先创建一个 HTML 表单,该表单将生成 CSV 文件。

<form>
  First name:<br>
  <input type="text" name="firstname">
  <br>
  Last name:<br>
  <input type="text" name="lastname">
   Email: <br>
  <input type="text" name="email">
</form>

让我们放置一些代码来创建 PHP 表单提交:

<?php
$email=$_POST['email'];
$firstName=$_POST['firstName'];
$lastName=$_POST['lastName'];

$to = "sample@ecomspark.com";
$subject = "Send Form data as CSV attachment and send email ";

$message = "".
"Email: $email" . "\n" .
"First Name: $firstName" . "\n" .
"Last Name: $lastName";

让我们编写 CSV 生成和 PHP 附件的代码:

<?php
//The Attachment

$cr = "\n";
$data = "Email" . ',' . "First Name" . ',' . "Last Name" . $cr;
$data .= "$email" . ',' . "$firstName" . ',' . "$lastName" . $cr;

$fp = fopen('file.csv','a');
fwrite($fp,$data);
fclose($fp);

//Make the attachment
$attachments[] = Array(
   'data' => $data,
   'name' => 'file.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" .
     "Cc: emaito@domain.com\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);
?>

将上述代码放在一起,您将能够在 PHP 中生成和通过电子邮件发送 CSV 文件。请随时在评论部分提出任何问题

Comments are closed.