Friday 8 November 2013

Easy PHP Email With Attachments using Swift Mailer Tutorial


This tutorial is about sending email in PHP using Swift Mailer which is flexible and elegant object-oriented approach to send emails with a multitude of features. You can also attach files as Attachments. Enjoy it.
  1. Swift Mailer integrates into any web app written in PHP 5, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features.
    • Send emails using SMTP, sendmail, postfix or a custom Transport implementation of your own.
    • Support servers that require username & password and/or encryption
    • Protect from header injection attacks without stripping request data content
    • Send MIME compliant HTML/multipart emails
    • Use event-driven plugins to customize the library
    • Handle large attachments and inline/embedded images with low memory use
  2. We will include swift mailer using below code.
    • // Swift Mailer library will be required. lib folder is available in source code.
      require_once 'lib/swift_required.php';
  3. Now we will include our connection configuration file like this if we want to include dynamic data from MySQL.
    • // For Dynamic contents we will add our config File
      include("configPDO.php");
      
  4. You will give SMTP Transport method here and provide details using below code for authentication.
    • // Create the Transport. we can put ip instead of smtp.example.org if we are on intranet.
      $transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)
        ->setUsername('your username')
        ->setPassword('your password')
        ;
  5. You could alternatively use a different transport such as Sendmail or Mail if required.
    • // Sendmail
      $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
      // Mail
      $transport = Swift_MailTransport::newInstance();
  6. Now we will create the Mailer using created trasnport. please see below code, It will use later for sending message.
    • // Create the Mailer using your created Transport
      $mailer = Swift_Mailer::newInstance($transport);
  7. Now we will start creating our message. first we will choose our mesage subject.
    • // Subject of the Message
      $message = Swift_Message::newInstance('Subject is Crewow Free Web Tutorials');
  8. Sender Address will be written like this.
    • // Address of Sender will be written in setFrom Function
      $message->setFrom(array('info@crewow.com' => 'Furqan Aziz'));
  9. Receiver emails will be written like this.
    • // Address of the recipients will be written in setTo 
      $message->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'));
  10. We can add CC and BCC for this message like the below code.
    • // You can add CC like this.
      $message->addCc('info@crewow.com');
      // You can add BCC like this.
      $message->addbCc('someone@crewow.com');
  11. For Dynamic data we can either use query or variables which can be set.
    • // For Dynamic contents you will add your config File
      include("configPDO.php");
  12. Here is sample for just one variable which we will use in body of the message.
    • // Define $field1 and $field2 for named placeholders
      $field1= "Center"; 
      $field2="Active"; 
      We can use query to get results from MySQL Database using prepared query with PDO. Here its for $CToday only
      $STM = $dbh->prepare("SELECT SrNo FROM YourTable WHERE field1 = :field1 AND field2 = :field2");
      // bind paramenters, Named paramenters alaways start with colon(:)
      $STM->bindParam(':field1', $field1);
      $STM->bindParam(':field2', $field2);
      // For Executing prepared statement we will use below function
      $STM->execute();
      // Count no. of records
      $CToday = $STM->rowCount();
    OR
  13. We can set all variables manually or get them using POST method from some form.
    • // We can set variables like this
      $NToday = 200;  //North Today
      $CToday = 300;  //Central Today
      $SToday = 400;  //South Today
      $TotalToday = $NToday + $CToday + $SToday;  //Total Today
  14. Here is example of setting body for simplest message
    • // For Simple message we do like this
      $message->setBody('Here is the message itself');
    OR
  15. We can use HTML and CSS Style to make it attactive and cool
    • // For HTML/PHP message you can do it like this
      $message->setBody(
      '<html>' .
      ' <head><style type=text/css>
      * { margin: 0; padding: 0; }
      body { font: 14px Georgia, serif; }
      
      #page-wrap { width: 1024px; margin: 0 auto; }
      
      table { border-collapse: collapse; width: 100%; }
      td, th { border: 1px solid #0099FF; padding: 10px; }
      
      .slim { width: 88px; background-color: #eee;  }
      .hover { background-color: #eee; }
      </style></head>' .
      ' <body>' .
      ' <label>Dear Crewow Team,</label><br />
      <br />
      Here is our new Tutorial. please check below link after the table<br />
      <br /> <table>
      
       <tr>
       <td class=slim align=center ><strong>Region</strong></td>
          <td class=slim align=center ><strong>Today</strong></td>
       </tr>
       
           <tr>
          <td align=center>North</td>
       <td align=center>'.$NToday.'</td>
       </tr>
        
        <tr>
          <td align=center>Central</td>
       <td align=center>'.$CToday.'</td>
       </tr>
       
          <tr>
          <td align=center>South</td>
       <td align=center>'.$SToday.'</td>
       </tr>
          <tr>
          <td align=center><strong>Grand Total</strong></td>
       <td align=center><strong>'.$TotalToday.'</strong></td>
       </tr>
      </table>
      <br />
      <span style=color:#9966FF:><b><a href=http://crewow.com/>Crewo Website</a></b></span>
      <br /> 
      Best Regards<br />
      <hr>
      CreWow Network | www.crewow.com <br />
      
      <br />' .
      ' </body>' .
      '</html>',
        'text/html' //Mark the content-type as HTML
      );
  16. We can attach files using below code. please read swift mailer documentation for more details.
    • //Below code can be used to attached excel. you can attach any file you want like pdf zip or any other. 
      $message->attach(Swift_Attachment::fromPath('Excel/SampeFile.xls'));
  17. Finally we will send email message via created mailer like this.
    • // Send the message
      $result = $mailer->send($message);
You can use Swift mailer for sending emails. For any query/suggestions please post a comment on our Facebook Page.


No comments:

Post a Comment