php php发送带附件的电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4586557/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:34:45  来源:igfitidea点击:

php send email with attachment

php

提问by Bharanikumar

How to send the email with resume attachment ,

如何发送带有简历附件的电子邮件,

i take snippet from this place Click here

我从这个地方取片段点击这里

In this site, snippet works fine,

在这个网站上,片段工作正常,

Even i got the mail, but attachment is not working, am getting attment as noname with 0kb

即使我收到了邮件,但附件不起作用,我收到了 0kb 的匿名文件

size file, What is Issue in that snippet ,

大小文件,该片段中有什么问题,

回答by dqhendricks

 function mail_attachment($to, $subject, $message, $from, $file) {
  // $file should include path and filename
  $filename = basename($file);
  $file_size = filesize($file);
  $content = chunk_split(base64_encode(file_get_contents($file))); 
  $uid = md5(uniqid(time()));
  $from = str_replace(array("\r", "\n"), '', $from); // to prevent email injection
  $header = "From: ".$from."\r\n"
      ."MIME-Version: 1.0\r\n"
      ."Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n"
      ."This is a multi-part message in MIME format.\r\n" 
      ."--".$uid."\r\n"
      ."Content-type:text/plain; charset=iso-8859-1\r\n"
      ."Content-Transfer-Encoding: 7bit\r\n\r\n"
      .$message."\r\n\r\n"
      ."--".$uid."\r\n"
      ."Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"
      ."Content-Transfer-Encoding: base64\r\n"
      ."Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n"
      .$content."\r\n\r\n"
      ."--".$uid."--"; 
  return mail($to, $subject, "", $header);
 }

回答by German Rumm

If you are NOT trying to learn how to do it by hand, and just want to send an email with attachment, then you are better of using some sort of library for that. I recommend SwiftMailer, I tried a lot of libraries and this one works best. Check how easy it is to add an attachment using SwiftMailer here: http://swiftmailer.org/docs/attaching-files

如果您不想学习如何手动完成,而只想发送带有附件的电子邮件,那么您最好为此使用某种库。我推荐SwiftMailer,我尝试了很多库,这个效果最好。在此处检查使用 SwiftMailer 添加附件是多么容易:http://swiftmailer.org/docs/attaching-files

回答by Michael Irigoyen

Your best bet is to use the Mime Mail PEAR library for handling attachments. It's much easier and cleaner and you'll be less prone to errors.

最好的办法是使用 Mime Mail PEAR 库来处理附件。它更容易、更干净,而且你也不太容易出错。

PEAR Mime Mail

PEAR Mime 邮件

You can attach files to an email simply like this:

您可以像这样简单地将文件附加到电子邮件中:

$headers['From'] = '[email protected]';
$headers['To'] = '[email protected]';
$headers['Subject'] = 'Email Subject';

$mime = new Mail_mime("\r\n");
$mime->setTXTBody('Email text');
$mime->addAttachment($filedata, 'application/octet-stream', 'filename', true, 'base64');

//Prepare the message to be sent
$body = $mime->get();
$headers = $mime->headers($headers);

//Send the message via SMTP
$mail_obj =& Mail::factory('smtp', array('host' => 'mail.domain.com', 'port' => 25));
$mail_obj->send($to, $headers, $body);

回答by André Figueira

If you just want to send a simple form with a single attachment this code is probably the best and easiest thing to use is the following code it works well.

如果您只想发送带有单个附件的简单表单,此代码可能是最好且最容易使用的方法,以下代码运行良好。

function submitSupportTicket() {

函数 submitSupportTicket() {

if(isset($_POST['submit']))
{

    $company = $_POST['company'];
    $url = $_POST['url'];
    $issue = $_POST['issue'];

    $screenshot = basename($_FILES['screenshot']['name']);

    $fileType = substr($screenshot, strrpos($screenshot, '.') + 1);

    $fileSize = $_FILES['screenshot']['size']/1024;

    $allowedFileTypes = array("jpg", "jpeg", "gif", "bmp", 'png');

    $allowedExt = false;

    for($i=0; $i<sizeof($allowedFileTypes); $i++)
    {

        if(strcasecmp($allowedFileTypes[$i],$fileType) == 0)
        {

            $allowedExt = true;

        }

    }

    if(!$allowedExt)
    {

        setMessage('The uploaded file is not supported file type. Only the following file types are supported: '.implode(',',$allowed_extensions), 0);
        header('Location: '.currentURL());
        exit;

    }

    $filePath = 'mediaLibrary/attachments'.$screenshot;

    $tmpPath = $_FILES['screenshot']['tmp_name'];

    if(is_uploaded_file($tmpPath))
    {

        if(!copy($tmpPath, $filePath))
        {

            echo 'There was an error attaching the file.';
            exit;

        }

    }

    $attachment = chunk_split(base64_encode(file_get_contents($_FILES['screenshot']['tmp_name'])));

    $fileName = $_FILES['screenshot']['name'];

    $boundary = md5(date('r', time())); 



    $headers = "From: [email protected]\r\nReply-To: [email protected]";
        $headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";

        $message = "This is a multi-part message in MIME format.

--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"

--_2_$boundary
Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit

Company: $company
URL: $url
Issue: $issue

Submitted from minttwist.com

--_2_$boundary--
--_1_$boundary
Content-Type: application/octet-stream; name=\"$filename\" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

$attachment
--_1_$boundary--";

    $to = '[email protected]';

    $subject = 'Support Request - '.$company;

    mail($to, $subject, $message, $headers);

    echo 'We have received your support request.';

    header('Location: '.currentURL());

}

}

回答by Jared Clemence

I did not see the answer to your question anywhere above, so I will attempt to provide a little more information that might help.

我在上面的任何地方都没有看到您的问题的答案,因此我将尝试提供更多可能有帮助的信息。

I had the same exact problem just today. I built a series of PDF files, which then were converted to a single tar.gz file and this file bundle I wanted to email to a human processing agent who would respond to these documents in kind. However, when I used the various scripts to generate the correct MIME message format, I ended up sending an attachment that was 0 kB in total size with the name "noname".

就在今天,我遇到了同样的问题。我构建了一系列 PDF 文件,然后将其转换为单个 tar.gz 文件,我想将此文件包通过电子邮件发送给人工处理代理,该代理会以实物形式回复这些文件。但是,当我使用各种脚本生成正确的 MIME 消息格式时,我最终发送了一个总大小0 kB的附件,名称为 "noname"

With so many people all providing the same answer, I thought to myself that there answers must be correct and that the problem must be somewhere else. The answer to the problem is not the formatting of the message content, nor is it in your headers. Everything there is correct. The problem lies in the mail applications that exist between your application and the recipient e-mail address.

这么多人都提供相同的答案,我心想答案一定是正确的,问题一定出在其他地方。问题的答案不是消息内容的格式,也不是您的标题。那里的一切都是正确的。问题在于您的应用程序和收件人电子邮件地址之间存在的邮件应用程序。

I moved my code to a production server and the message sent without any problems, and the same file that previously sent as "noname 0kb" now was sent as "MikeyPoochigian_2013_05_10__16_28_27.tar.gz 241kb".

我将我的代码移到生产服务器,消息发送没有任何问题,以前作为“noname 0kb”发送的同一个文件现在被发送为“MikeyPoochigian_2013_05_10__16_28_27.tar.gz 241kb”。

I don't know yet what causes this particular failure, but I imagine it is a similar answer to one that I learned earlier this year when my mail application was sending to gmail but not sending to other mail servers. In that particular case, the mail applications were filtering content for SPAM between my development laptop (which had the internal domain of DevelopmentLaptop.local) and the final e-mail address. Because my originating server sent from the domain "DovelopmentLaptop.local", and because this domain was not registered with any DNS as a known address, those mail servers interpreted my test messages as spam. I suspect the same problem is interfering now with the messages that are being sent.

我还不知道是什么导致了这个特殊的失败,但我想这与我今年早些时候在我的邮件应用程序发送到 gmail 但不发送到其他邮件服务器时学到的答案类似。在那个特殊情况下,邮件应用程序在我的开发笔记本电脑(它具有 DevelopmentLaptop.local 的内部域)和最终电子邮件地址之间过滤垃圾邮件内容。因为我的原始服务器从域“DovelopmentLaptop.local”发送,并且因为这个域没有注册任何 DNS 作为已知地址,这些邮件服务器将我的测试邮件解释为垃圾邮件。我怀疑同样的问题现在正在干扰正在发送的消息。

Long answer now short (if that is possible), try porting your code to a production server with a registered public domain and see if it works. If it does, then it is not your code that needs to be fixed. Your code is likely to be fine.

长答案现在短(如果可能的话),尝试将您的代码移植到具有注册公共域的生产服务器,看看它是否有效。如果是这样,那么不需要修复您的代码。您的代码可能没问题。