Attach File Through PHP Mail

2019-03-04 02:39发布

I am trying to get a custom contact form using PHP mail to have a user attach a photo, that then gets sent to the recipient outlined in the PHP mail code

<input type="file" id="file" name="file">

The form code is as follows;

<form action="register-mail.php" method="POST" enctype="multipart/form-data">
 <input type="file" id="file" name="file">
 <input type="submit" value="Submit">
</form>

The PHP mail code is as follows;

<?php $file = $_FILES['file'];
 $formcontent="Email Text Content";
 $recipient = "fake@email.com";
 $subject = "Here is a Photo";
 $mailheader = 'From: Basic Sign-up <fake@email.com>' . "\r\n";
 mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
die();
?>

I can't seem to get it to attach the file to the email being sent. What am I doing wrong?

1条回答
放我归山
2楼-- · 2019-03-04 03:27

That is not how attachment works. Using the mail() for attachments is a little more complex than that. You got to tell mail() which part should handle the file attachment and which part is responsible to display the email body by setting up a MIME Boundary. In other words, the code should be divided into 2 parts:

  • A section to handle the message being sent in body
  • A section to handle file uploading

A detailed tutorial is here

PHP EMAIL WITH ATTACHMENT

However, I would suggest you to use a very handy tool called PHPMailer to do the same task. It simplifies the process and lets the class handle all the legwork.

PHPMailer

查看更多
登录 后发表回答