PHP SMTP Emails using SwiftMailer
SwiftMailer 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.
This post describe how to use swiftmailer to send an PHP SMTP Emails.
Download it
first of all we should download the swiftmailer lib. it is free, and we can download it from its website http://swiftmailer.org/
Requirements
We need four parameters to connect to SMTP service
- Server or Host
- Port
- Username
- Password
and this parameters is differ from one accout to another and from one server to another.

you can get your smtp information from your site cpanel
CPanel > E-Mail Accounts > (for every account there is a Configure Email Client)
Use it
include the lib into your code :
require_once 'path-to-swiftmailer-library/swift_required.php';
connect to SMTP server with your info (Host, Port, Email and Password)
$transport = Swift_SmtpTransport::newInstance("$host", $port)
->setUsername("$email")
->setPassword("$password");
$mailer = Swift_Mailer::newInstance($transport);
Prepare the Message : (title, sender E-Mail, sender name, reciever E-Mail and message content)
$message = Swift_Message::newInstance("$title")
->setFrom(array("$sender_email" => "$sender_name"))
->setTo(array("$reciever_email"))
->setBody($message_content,'text/html');
finally, send the message :
$result = $mailer->send($message);
to check if the message was sent or failed :
if ($result) {
echo 'Sent';
} else {
echo 'Failed';
}
The Result (full code)
require_once 'path-to-swiftmailer-library/swift_required.php';
$transport = Swift_SmtpTransport::newInstance("$host", $port)
->setUsername("$email")
->setPassword("$password");
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance("$title")
->setFrom(array("$sender_email" => "$sender_name"))
->setTo(array("$reciever_email"))
->setBody($message_content,'text/html');
$result = $mailer->send($message);
if ($result) {
echo 'Sent';
} else {
echo 'Failed';
}
The list of Variable used :
- $host : the website or server used to send messages (mail.website.com or smtp.website.com)
- $port : the port used for sending smtp messages (21, 26 ..)
- $email : your email that you will send by (it must be in the same domain as Host) (admin@website.com)
- $password : your email password
You can send using google mail service (Gmail) :
- $host : smtp.gmail.com
- $port : 465
- $email : Your full Gmail address (e.g. example@gmail.com)
- $password : Your Gmail password
other code variables :
- $title : your message title
- $sender_email : the same as $email that is used to send
- $sender_name : you can choose any name or you can use the message title
- $reciever_email : the E-Mail address that you are sending the message to
- $message_content : your message (you can use HTML tags in message)







