14

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

size file, What is Issue in that snippet ,

2
  • possible duplicate of Send email with attachments in PHP? Commented Jan 3, 2011 at 17:13
  • Please search for existing questions/answers before you post a question - this isn't exactly new ground and people probably aren't going to be inclined to debug some script you picked up on the internet. Commented Jan 3, 2011 at 17:14

5 Answers 5

39
 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);
 }
Sign up to request clarification or add additional context in comments.

6 Comments

Yes, wrote this years ago and haven't really looked at the code since. I cleaned it up greatly just now. The code is now untested however. Should be exact same though...just less lines and more efficient.
:) Maybe a little space before the return? And I would include a charset parameter optimum, $pCharset = "ISO-8859-1"
above snippet not worked for me, still am getting file like none and size okb
What file type is it? May want to try playing around with this line: "Content-Type: application/octet-stream", and try switching it to the appropriate type.
If you are having difficulties with this code, investigate your mail transport agent settings -- wasn't working on my dev server because of misconfiguration, but worked fine on production server that a coworker set up. @dqhendricks, thanks so much -- I was able to take your code and basically copy and paste the plaintext message header right below itself and switch mime type to text/html so that the email sent in plaintext + html + successful file attachment (you can change attachment mime types really easily too!), thank you sir, cleanest example I've found for working with php mail() func!
|
3

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

2 Comments

but doesn't this require installing SwiftMailer onto your server?? ... many webhosts do not allow installing of additional modules/libraries.
SwiftMailer is a library, so there's nothing to "install" - just upload source files and use them.
2

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.

PEAR Mime Mail

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);

4 Comments

PEAR is not PERL. PEAR is a framework and distribution system for reusable PHP components. pear.php.net
Read a little fast over. Anyway, this seems a bit overklill for such an easy thing.
It's really not overkill at all. You don't have to manually maintain the MIME boundaries. That's a huge advantage in itself.
It is a year since I went from php, but I've set MIME boundaries of setting header. Unless the OP knows what HTTP headers are, I would say that it is good to use a framework that makes it even.
0

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() {

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());

}

}

Comments

-1

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".

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".

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.

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.