Send emails using php

Php email function : 


For your websites or web apps php provide a awesome feature i.e mail() function now you can send mails from your web site easily here is the code to send the mail



 <?php
  $to = "email_of_recipient@gmail.com";
  $subject = "Enter the subject";
  $txt = "i am sending test mail using php";
  $headers = "From: sender_email@yahoo.com" . "\r\n" .
  "CC: email_of_recipient@gmail.com".
  "BCC: email_of_2ndrecipient@gmail.com";
   mail($to,$subject,$txt,$headers);
 ?>


Php email with attachment


php provide a easy way to send emails but now its time to move on we can send attachment in the emails.The attachment can be of different type it can be a pdf file or it can be a image file or text file




  <?php

    //it is email adress who will receive the mail

    $to = 'email_of_recipient@gmail.com';

    //sender email address

    $from = 'sender_email@yahoo.com';

    $from_sender_name = 'xyz';

    //email subject

    $subject = 'email with attachment'; 

    //path to file attachment

    $file = "demo.pdf";

    //email body content

    $Content = '<h1>PHP Email with Attachment </h1>

    <p>This email has sent from xyz hello world.</p>';

    //header for sender information

    $headers = "From: $from_sender_name"." <".$from.">";

    //boundary for email

    $rand_time = md5(time()); 

    $mime_boundary = "==Multipart_Boundary_x{$rand_time}x"; 

    //headers for file attachment 

    $headers .= "\nMIME-Version: 1.0\n" .

    "Content-Type: multipart/mixed;\n" . 
    " boundary=\"{$mime_boundary}\""; 

   //multipart boundary for attachment 

   $message = "--{$mime_boundary}\n" . 
   "Content-Type: text/html; charset=\"UTF-8\"\n" .
    "Content-Transfer-Encoding: 7bit\n\n" . $Content . "\n\n"; 

  //preparing attachment in mail

    if(!empty($file) > 0){

      if(is_file($file)){

        $message .= "--{$mime_boundary}\n";

        $fp =    @fopen($file,"rb");

        $data =  @fread($fp,filesize($file));

        @fclose($fp);

        $data = chunk_split(base64_encode($data));

        $message .= "Content-Type: application/octet-stream;
        name=\"".basename($file)."\"\n" . 

        "Content-Description: ".basename($files[$i])."\n" .

        "Content-Disposition: attachment;\n" . 
        " filename=\"".basename($file)."\"; size=".
        filesize($file).";\n" . 
           "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";

    }

   }

   $message .= "--{$mime_boundary}--";

   $returnpath = "-f" . $from;

   //send email function

   $mail = @mail($to, $subject, $message, $headers, $returnpath); 

   //email sending status

   echo $mail?"<h1>Mail sent.</h1>":"<h1>Mail not sent.</h1>";

  ?>

Now the email functionality for sending the attachment has been increased if you want to learn sending email with muliple attachment kindly click below

No comments:

Post a Comment