通过 PHP 邮件附加文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11961969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Attach File Through PHP Mail
提问by Be Right Bacon
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
我正在尝试使用 PHP 邮件获取自定义联系表单,让用户附加照片,然后将其发送给 PHP 邮件代码中列出的收件人
<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邮件代码如下;
<?php $file = $_FILES['file'];
$formcontent="Email Text Content";
$recipient = "[email protected]";
$subject = "Here is a Photo";
$mailheader = 'From: Basic Sign-up <[email protected]>' . "\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?
我似乎无法将文件附加到正在发送的电子邮件中。我究竟做错了什么?
回答by asprin
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:
这不是依恋的运作方式。使用mail()for 附件比这要复杂一些。您必须mail()通过设置MIME Boundary来告诉哪个部分应该处理文件附件,哪个部分负责显示电子邮件正文。换句话说,代码应该分为两部分:
- A section to handle the message being sent in body
- A section to handle file uploading
- 处理在正文中发送的消息的部分
- 处理文件上传的部分
A detailed tutorial is here
详细教程在这里
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 的非常方便的工具来完成相同的任务。它简化了流程,让班级处理所有跑腿工作。

