Monday, March 24, 2014

PHP Code To Send Email With Swiftmailer Library

Before use this function, please download swiftmailer library from this source http://swiftmailer.org/download. This function can send email using PHP with Swiftmailer Library. Place This file in same path with folder 'lib/'. This function is automatic detect body of message in plain text or html. Here the code:
function sendEmail($method,$subject,$from,$to,$body){
require_once dirname(__FILE__).'/lib/swift_required.php';
if($method=="smtp"){
$smtp     = "smtpaddress"; // ex: smtp.mandrillapp.com
$port     = 587; // ex: 587
$username = "yourusername"; // ex: blabla@gmail.com
$password = "yourpassword"; // ex: passwordtoaccess
$transport = Swift_SmtpTransport::newInstance($smtp, $port)
   ->setUsername($username)
   ->setPassword($password);
}
else if($method=="sendmail"){
   $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
}
else if($method=="mail"){
   $transport = Swift_MailTransport::newInstance();
}
else{
   $transport = Swift_MailTransport::newInstance();
}
// auto detect plain text or html
if($body != strip_tags($body)){$text="text/html";}
else{$text="text/plain";}

$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance($subject)
   ->setFrom($from)
   ->setTo($to)
   ->setBody($body,$text);

$result = $mailer->send($message);
return $result;
}

// sample send email using smtp method
$method  = "smtp";
$subject = "It's cool";
$from    = array("youremail@blabla.com" => "iben");
$to      = array("yourdestination@blabla.com" => "my dear");
$body    = "<b>It's great script made by iben</b>";
$send    = sendEmail($method,$subject,$from,$to,$body);

echo $send; // output: true or false

// To send with other method just change $method to your prefer (sendmail, mail, or smtp)

Good Luck !!!

0 comments:

Post a Comment