SitePoint Sponsor

User Tag List

Results 1 to 12 of 12
  1. #1
    SitePoint Zealot asrasrasr's Avatar
    Join Date
    Apr 2009
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Send pdf file as attachment in email

    Hello friends,

    I am trying to send a pdf file as attchment in my email.

    Using following code.

    Code PHP:
              <?php
     
        $to = "poojajadon@gmail.com";
     
        $from = "test@gmail.com";
     
        $subject = "Here is your attachment";
     
        $fileatt = "mypdf.pdf";
     
        $fileatttype = "application/pdf";
     
        $fileattname = "newname.pdf";
     
        $headers = "From: $from";
     
    	$file = fopen( $fileatt, "rb" );
     
    	$data = fread( $file, filesize( $fileatt ) );
     
    	fclose( $file );
     
     
    	$semi_rand = md5( time() );
     
        $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
     
        $headers .= "MIME-Version: 1.0n" . "Content-Type: multipart/mixed;n" . "boundary=\"{$mime_boundary}\"\r";
     
        $message = "This is a multi-part message in MIME format.nn" ."{$mime_boundary}n" . 
     
    	"Content-Type: text/plain; charset=\"iso-8859-1\"\r\n" .
     
        "Content-Transfer-Encoding: 7bitnn" .
     
    $message . "nn";
     
    $data = chunk_split( base64_encode( $data ) );
     
    $message .= "{$mime_boundary}n" .
     
    "Content-Type: {$fileatttype};n" .
     
    " name=\"{$fileattname}\"\n" .
     
    "Content-Disposition: attachment;n" .
     
    "filename=\"{$fileattname}\"\n" .
     
    "Content-Transfer-Encoding: base64nn" .
     
    $data . "nn" .
     
    "{$mime_boundary}n";
     
     
    if( mail( $to, $subject, $message, $headers ) ) {
     
    echo "<p>The email was sent.</p>";
     
    }
     
    else {
     
    echo "<p>There was an error sending the mail.</p>";
     
    }
        ?>

    But i an uable to send pdf as attchment. This code send email successfully. but without attchment.

    Email format is:

    This is a multi-part message in MIME format.nn==Multipart_Boundary_x2645f9aa32004099fecb2e28cd3914ccxnContent-Type: text/plain; charset="iso-8859-1"
    Content-Transfer-Encoding: 7bitnnnn==Multipart_Boundary_x2645f9aa32004099fecb2e28cd3914ccxnContent-Type: application/pdf;n name="newname.pdf"
    Content-Disposition: attachment;nfilename="newname.pdf"
    Content-Transfer-Encoding: base64nnJVBERi0xLjMKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL1Jlc291cmNlcyAy
    IDAgUgovQ29udGVudHMgNCAwIFI+PgplbmRvYmoKNCAwIG9iago8PC9GaWx0ZXIgL0ZsYXRlRGVj
    b2RlIC9MZW5ndGggODE2Pj4Kc3RyZWFtCnicrVbbcts2EH33V+xjO7UgXEkiT/FF6bj1tE6l1tO8
    IQRsoTIJBQQt+2/6Lf2yghdVdFhZjpPRjKiBztmzu1gcgsJPRxiJFDZHn0AyJDjg+CEMZRhohpiA
    DAvECeQFTC8InDt4f3S6gOk7AhnCGBY3MFtsVwj9bIkCEU+WaEpQKiFNEiQoLDR8d1HeO5ub72Hx
    V8TsAJFHQRCUSJhglArwBm72SVNIn6wwgkgMEvOhrFWZh1pbFwsjvdCXRUpkxIk20qW9MVV4vDOg
    Sg1nriiMz626g6ulC+7Wq/XyESZw5o0K9t6GRzAPa5MHo1uCypfW3BuNXpdHFncma/OgfEIzmAe4
    NK5UXlfwm1P6GK5tqSvnj+HU+FW1tN4gmF9yYKenr5NMJEpJKzmDqm3j23rV/YjtRLlD9ep1kYVA
    eHJlZgoyMDIzNwolJUVPRgo=
    nn==Multipart_Boundary_x2645f9aa32004099fecb2e28cd3914ccxn

    Without any attchment.

    Please where i m wrong?

  2. #2
    play of mind Ernie1's Avatar
    Join Date
    Sep 2005
    Posts
    1,252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    <?php

    $to 
    "poojajadon@gmail.com";
    $from "test@gmail.com";
    $subject "Here is your attachment";
    $mess "test message";
    $fileatt "mypdf.pdf";
    $fileatt_type "application/pdf";
    $fileatt_name "mypdf.pdf";
    $headers "From: $from";
    $file fopen($fileatt"rb");
    $data fread($filefilesize($fileatt));
    fclose($file);

    $semi_rand md5(time());
    $mime_boundary "==Multipart_Boundary_x{$semi_rand}x";

    // Add the headers for a file attachment
    $headers .= "\nMIME-Version: 1.0\r\n" .
              
    "Content-Type: multipart/mixed;\r\n" .
              
    " boundary=\"{$mime_boundary}\"";

    // Add a multipart boundary above the plain message
    $message "This is a multi-part message in MIME format.\r\n\r\n" .
             
    "--{$mime_boundary}\r\n" .
             
    "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n" .
             
    "Content-Transfer-Encoding: 7bit\r\n\r\n" .
             
    $mess "\r\n\r\n";

    // Base64 encode the file data
    $data chunk_split(base64_encode($data));

    // Add file attachment to the message
    $message .= "--{$mime_boundary}\r\n" .
              
    "Content-Type: {$fileatt_type};\r\n" .
              
    " name=\"{$fileatt_name}\"\r\n" .
              
    "Content-Transfer-Encoding: base64\r\n\r\n" .
              
    $data "\r\n\r\n" .
              
    "--{$mime_boundary}--\r\n";

    if (
    mail($to$subject$message$headers))
    {
        echo 
    "<p>The email was sent.</p>";
    }
    else
    {
        echo 
    "<p>There was an error sending the mail.</p>";
    }
    my mobile portal
    ghiris.ro

  3. #3
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I would recommend the well known and easy to use PHPMailer class to use.
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  4. #4
    SitePoint Zealot asrasrasr's Avatar
    Join Date
    Apr 2009
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Can i attach a PDF file which generate on the fly?

  5. #5
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by asrasrasr View Post
    Can i attach a PDF file which generate on the fly?
    If you are asking the possibility with PHPMailer class, you should save the file in a loation first then send it by attaching and delete it after sending is successful.
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  6. #6
    SitePoint Zealot asrasrasr's Avatar
    Join Date
    Apr 2009
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    But i an unable to sava file autimatically. How can this posible ?

  7. #7
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What library are you using to create PDF first? How are you generating PDF content/data on the fly? AFAIK, It should be possible to save as a file whatever you are using to generate PDFs from PHP.
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  8. #8
    SitePoint Zealot asrasrasr's Avatar
    Join Date
    Apr 2009
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    i am trying following code;

    Code PHP:
    <?php $db=mysql_connect("localhost", "root","") or die("Sorry, connection problem...");
           mysql_select_db("studio",$db);
     
    	//require('check_login.php'); 
    	require_once("fpdf/fpdf.php");
     
    	$query="select * from gad_invoices where invoice_id='".$_REQUEST[invoice_id]."'";
    	$result = mysql_query($query);
    	 while($row = mysql_fetch_array($result))
    	  {
    		$invoice_id =$row['invoice_id'];
    		$status = $row['active'];
    		$idate =  $row['invoice_date'];
    		$customers_id = $row['customers_id'];
    		$onumber = $row['order_id'];
    		$company=$row['company_name'];
    		$address=$row['address'];
    		$state=$row['state'];
    		$zip=$row['postal_code'];
    		$phone=$row['phone_number'];
    		$fax=$row['fax_number'];
    		$email=$row['emailid'];
    		$cname=$row['contact_name'];
    		$contact_name=html_entity_decode($cname,ENT_QUOTES);
    		$cname=$row['contact_name'];
    		$product_name = $row['product_name'];
    		$product_description = $row['product_description'];
    		$quantity = $row['quantity'];
    		$unit_price = $row['unit_price'];
    		$extra = $row['extra'];
    		$discount = $row['discount'];
    		$deposits = $row['deposits'];
    	  }
     
     
    class PDF extends FPDF
    {
        var $widths;
        var $aligns;
        var $head_str;
    //Page header
    function Header()
    {
        //global $site_name;
        //Logo
        $this->Image('images/logo.jpg',10,8,33);
        //Arial bold 15
        $this->SetFont('Courier','',8);
        //Get the width of the String
        foreach($this->head_str as $hd_str)
        {
            if($sname_width<$this->GetStringWidth($hd_str))
            {
                $sname_width=$this->GetStringWidth($hd_str);
            }
        }
        foreach($this->head_str as $hd_str)
        {
            //Title
            $this->Cell(0,6,$hd_str,0,0,'R');
            $this->Ln(5);
        }
        //Line break
        $this->Ln(0);
    }
     
    //set the header
    function SetHeaderString($headstr)
    {
        $this->head_str=explode('-',$headstr);
    }
     
    //Page footer
    function Footer()
    {
        //Position at 1.5 cm from bottom
        $this->SetY(-15);
        //Arial italic 8
        $this->SetFont('Arial','I',8);
        //Page number
        $this->Cell(0,10,'Studio 131  -  Page '.$this->PageNo().'/{nb}',0,0,'C');
    }
     
    function Heading($string)
    {
        //go to the next line
        $this->Ln(5);
        //Arial bold 15
        $this->SetFont('Arial','BU',15);
        //Heading
        $this->Cell(0,10,$string,0,0,'C');
        //Line break
        $this->Ln(15);
        //set back the font
        $this->SetFont('Courier','',8);
    }
     
    function InnerText($string)
    {
        //go to the next line
        $this->Ln(5);
        //Arial bold 15
        $this->SetFont('Arial','B',7);
        //Heading
        $this->Cell(0,10,$string,0,0,'L');
        //Line break
        $this->Ln(0);
        //set back the font
        $this->SetFont('Courier','',8);
    }
     
    function SetWidths($w)
    {
        //Set the array of column widths
        $this->widths=$w;
    }
     
    function SetAligns($a)
    {
        //Set the array of column alignments
        $this->aligns=$a;
    }
     
    function Row($data)
    {
        //Calculate the height of the row
        $nb=0;
        for($i=0;$i<count($data);$i++)
        {
            $nb=max($nb,$this->NbLines($this->widths[$i],$data[$i]));
            //check for image
            $temp=explode("|",$data[$i]);
            if($temp[0]=="##image")
            {
                //print the image
                if(($nb*5)<40)
                {
                    $nb=8;
                }
            }
        }
        $h=5*$nb;
        //Issue a page break first if needed
        $this->CheckPageBreak($h);
        //Draw the cells of the row
        for($i=0;$i<count($data);$i++)
        {
            $w=$this->widths[$i];
            $a=isset($this->aligns[$i]) ? $this->aligns[$i] : 'L';
            //Save the current position
            $x=$this->GetX();
            $y=$this->GetY();
            //Draw the border
            $this->Rect($x,$y,$w,$h);
            //check for image
            $temp=explode("|",$data[$i]);
            if($temp[0]=="##image")
            {
                //check if image exists
                if(file_exists($temp[1]))
                {
                    //print the image
                    $this->Image($temp[1],$x+3.5,$y+3.5,33,33);
                }
                else
                {
                    //Print the error text
                    $this->MultiCell($w,5,"Invalid Image",0,$a);
                }
            }
            else
            {
                //Print the text
                $this->MultiCell($w,5,$data[$i],0,$a);
            }
            //Put the position to the right of the cell
            $this->SetXY($x+$w,$y);
        }
        //Go to the next line
        $this->Ln($h);
    }
     
    function CheckPageBreak($h)
    {
        //If the height h would cause an overflow, add a new page immediately
        if($this->GetY()+$h>$this-> PageBreakTrigger)
            $this->AddPage($this->CurOrientation);
    }
     
    function NbLines($w,$txt)
    {
        //Computes the number of lines a MultiCell of width w will take
        $cw=&$this->CurrentFont['cw'];
        if($w==0)
            $w=$this->w-$this->rMargin-$this->x;
        $wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
        $s=str_replace("\r",'',$txt);
        $nb=strlen($s);
        if($nb>0 and $s[$nb-1]=="\n")
            $nb--;
        $sep=-1;
        $i=0;
        $j=0;
        $l=0;
        $nl=1;
        while($i<$nb)
        {
            $c=$s[$i];
            if($c=="\n")
            {
                $i++;
                $sep=-1;
                $j=$i;
                $l=0;
                $nl++;
                continue;
            }
            if($c==' ')
                $sep=$i;
            $l+=$cw[$c];
            if($l>$wmax)
            {
                if($sep==-1)
                {
                    if($i==$j)
                        $i++;
                }
                else
                    $i=$sep+1;
                $sep=-1;
                $j=$i;
                $l=0;
                $nl++;
            }
            else
                $i++;
        }
        return $nl;
    }
     
     
    function CheckImage($img_name)
    {
        $extension=pathinfo($img_name,PATHINFO_EXTENSION);
        if($img_name!="" && (strtolower($extension)=="jpg" || strtolower($extension)=="gif" || strtolower($extension)=="png" || strtolower($extension)=="jpeg"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
     
    function ShowData($label,$text,$image,$path)
    {
        if($text!="" && $image!="")
        {
            $this->Multicell(0,10,$label.$text,0,l);
            $this->Ln(10);
            if($this->CheckImage($image))
            {
                if(file_exists("../".$path.$image))
                {
                    $this->Image("../".$path.$image,12,$this->GetY,33);
                    $this->Ln(10);
                }
            }
        }
        else if($text=="" && $image!="")
        {
            if($this->CheckImage($image))
            {
                if(file_exists("../".$path.$image))
                {
                    $this->Multicell(0,10,$label.$text,0,l);
                    $this->Ln(10);
                    $this->Image("../".$path.$image,12,$this->GetY,33);
                    $this->Ln(10);
                }
            }
        }
        else if($text!="" && $image=="")
        {
            $this->Multicell(0,4,$label.$text,0,l);
            $this->Ln(4);
        }
    }
    function ErrText($errstring)
    {
        $this->CheckPageBreak(15);
        //$this->Ln(15);
        $this->SetTextColor(255,0,0);
        $this->Cell(0,10,$errstring,0,0,'C');
        $this->SetTextColor(0,0,0);
        $this->Ln(15);
     
    }
     
    function ItemText($errstring)
    {
       // $this->CheckPageBreak(15);
    	$this->SetXY(10,170);
        //$this->Ln(15);
        $this->SetTextColor(255,0,0);
        $this->Cell(0,10,$errstring,0,0,'L');
        $this->SetTextColor(0,0,0);
        $this->Ln(15);
     
    }
     
    function QuantityText($errstring)
    {
        //$this->CheckPageBreak(15);
    	$this->SetXY(70,170);
        //$this->Ln(15);
        $this->SetTextColor(255,0,0);
        $this->Cell(0,10,$errstring,0,0,'L');
        $this->SetTextColor(0,0,0);
        $this->Ln(15);
     
    }
     
    function UnitText($errstring)
    {
        //$this->CheckPageBreak(15);
    	$this->SetXY(100,170);
        //$this->Ln(15);
        $this->SetTextColor(255,0,0);
        $this->Cell(0,10,$errstring,0,0,'L');
        $this->SetTextColor(0,0,0);
        $this->Ln(15);
     
    }
     
    function AmountText($errstring)
    {
        //$this->CheckPageBreak(15);
    	$this->SetXY(130,170);
        //$this->Ln(15);
        $this->SetTextColor(255,0,0);
        $this->Cell(0,10,$errstring,0,0,'L');
        $this->SetTextColor(0,0,0);
        $this->Ln(15);
     
    }
     
     
     
    function SetLineBreak()
    {
        $this->Ln(10);
        $this->Line($this->GetX(),$this->GetY(),($this->GetX()+180),$this->GetY());
    }
     
    }
     
    //Instanciation of inherited class
    $pdf=new PDF();
    $pdf->SetHeaderString($site_name);
    $pdf->AliasNbPages();
    $pdf->AddPage();
    $pdf->SetFont('Courier','',12);
     
    #######Site Summery>>>>>>>>>
    $pdf->Heading("Invoice");
    $pdf->InnerText("Studio 131");
    $pdf->InnerText("Lifestyle and Commercial Photography - Creativity expected and achieved.");
    $pdf->InnerText("24-28 St Leonards Road, Windsor, Berkshire. SL4 3BB");
    $pdf->InnerText("E [email]studio@ukstudio131.co.uk[/email]");
    $pdf->InnerText("W http://www.ukstudio131.co.uk");
    $pdf->InnerText("");
    $pdf->InnerText("");
    $pdf->ShowData('Invoice number  : ',$invoice_id,"","");
    $pdf->ShowData('Invoice date  : ',$idate,"","");
    $pdf->ShowData('Order number  : ',$onumber,"","");
    $pdf->ShowData('Invoice status  : ',$status,"","");
    $pdf->ShowData('Company name  : ',$company,"","");
    $pdf->ShowData('Address  : ',$address,"","");
    $pdf->ShowData('State  : ',$state,"","");
    $pdf->ShowData('ZipCode  : ',$zip,"","");
    $pdf->ShowData('Phone  : ',$phone,"","");
    $pdf->ShowData('Fax  : ',$fax,"","");
    $pdf->ShowData('Email  : ',$email,"","");
    $pdf->ShowData('Contact name  : ',$contact_name,"","");
     
    $pdf->ItemText("Item");
    $pdf->QuantityText("Quantity");
    $pdf->UnitText("Unit price");
    $pdf->AmountText("Amount");
     
    $mcname1=explode("#", $product_name);
      $count1=count($mcname1);
      $y=170;
         for($j=0;$j<$count1-1;$j++) {
      $y=$y+5;
    $pdf->SetFont('Courier','',8);
    $pdf->SetXY(10, $y);
    $pdf->Cell(0,10,$mcname1[$j],0,0,'L');
    }
     
     
     $mcname1=explode(",", $quantity);
      $count1=count($mcname1);
      $y=170;
         for($j=0;$j<$count1-1;$j++) {
      $y=$y+5;
    $pdf->SetFont('Courier','',8);
    $pdf->SetXY(75, $y);
    $pdf->Cell(0,10,$mcname1[$j],0,0,'L');
    }
     
     
     
      $mcname1=explode(",", $unit_price);
      $count1=count($mcname1);
      $y=170;
         for($j=0;$j<$count1-1;$j++) {
      $y=$y+5;
    $pdf->SetFont('Courier','',8);
    $pdf->SetXY(100, $y);
    $pdf->Cell(0,10,$mcname1[$j],0,0,'L');
    }
     
     
     
     
    $mcname=explode(",", $unit_price);
    $count=count($mcname);
     
    $subtotal1=0;
    $mcname1=explode(",", $quantity);
    $count1=count($mcname1);
    $y=170;
    for($j=0;$j<$count1-1;$j++) {
    $y=$y+5;
    $uamount1= $mcname[$j]*$mcname1[$j];
    $uamount=number_format($uamount1,2,'.',',');
    $subtotal1=$subtotal1+$uamount;
    $sub_total=number_format($subtotal1,2,'.',',');
    $grand_total1=$subtotal1+$extra;
    $grand_total2=$grand_total1-$discount-$deposits;
    $grand_total=number_format($grand_total2,2,'.',',');
    $pdf->SetFont('Courier','',8);
    $pdf->SetXY(130, $y);
    $pdf->Cell(0,10,$uamount,0,0,'L');
     
    }
    $pdf->InnerText("");
    $pdf->InnerText("");
    $pdf->InnerText("");
    $pdf->ShowData('Sub Total  : ',$sub_total,"","");
    $pdf->ShowData('Extra  : ',$extra,"","");
    $pdf->ShowData('Discount  : ',$discount,"","");
    $pdf->ShowData('Deposits  : ',$deposits,"","");
    $pdf->ShowData('Grand Total  : ',$grand_total,"","");
     
     
     
     
     
    #######Building Pre Plans Ends>>>>>>>>>
     header('Content-type: "application/pdf"; charset="iso-8859-1"');
     header('Content-disposition: attachment; filename="mypdf.mypdf"');
     readfile('path_to_pdfs' . $pdf->Output()); 
    ?>

    but this code return nothing.

  9. #9
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The following will save your PDF (if the above code is error free to generate PDF);
    PHP Code:
    $pdf->Output($filename"F"); 
    And you can attach the $filename to your email and if you do not need it then you can also delete it with unlink() after email send is successful.
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  10. #10
    SitePoint Zealot asrasrasr's Avatar
    Join Date
    Apr 2009
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    $pdf->Output($filename, "F");

    this is not working successfully. The save pdf file not opened.

    But my code is working successfully.

  11. #11
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Did you replace:
    PHP Code:
    #######Building Pre Plans Ends>>>>>>>>>
     
    header('Content-type: "application/pdf"; charset="iso-8859-1"');
     
    header('Content-disposition: attachment; filename="mypdf.mypdf"');
     
    readfile('path_to_pdfs' $pdf->Output()); 
    with
    PHP Code:
    $pdf->Output('path/to/file/to/save/myfile.pdf'"F"); 
    ?
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  12. #12
    SitePoint Zealot asrasrasr's Avatar
    Join Date
    Apr 2009
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks rajug.
    Now i m successfully download pdf file.

    I have used $filename= "mypdf"; instead of

    $filename= "mypdf.pdf";

    When i changed mypdf with mypdf.pdf.

    I download file.

    Thanks alot


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •