Sending mail using SMTP with PHPMailer
Jon Moffet
PHPMailer is a simple PHP class for sending emails from your web application.
Unlike the default mail() function, PHPMailer supports sending email from your own authenticated SMTP server instead of relying on shared hosting server for sending mails.
PHPMailer is also less vulnerable to Email Injection Attack which is notorious with the default PHP mail() function
Other PHPMailer features includes :
- Easy facility for sending attachment
- Easy to use Object Oriented PHP class
- Support Sending HTML Email from scripts
- Multipart/alternative emails for mail clients that do not read HTML email
- Portable - it works on Linux/BSD/Windows platform without modification
Here's how to use PHPMailer in your scripts (snippets)
-
require("phpmailer/class.phpmailer.php");
-
-
//****
-
//PLEASE CHANGE THE SETTINGS HERE !!!!
-
//change settings here
-
$your_email = "info@example.com";
-
$your_smtp = "mail.example.com";
-
$your_smtp_user = "info@example.com";
-
$your_smtp_pass = "example_password";
-
$your_website = "http://example.com";
-
//****
-
-
-
//get contact form details
-
$name = $_POST['name'];
-
$email = $_POST['email'];
-
$url = $_POST['url'];
-
$comments = $_POST['comments'];
-
-
$response="Name: $name\nContents:\n$comments\n";
-
-
-
$mail = new PHPmailer();
-
-
$mail = $mail->SetLanguage("en", "phpmailer/language");
-
-
$mail->From = $your_email;
-
$mail->FromName = $your_website;
-
$mail->Host = $your_smtp;
-
$mail->Mailer = "smtp";
-
$mail->Password = $your_smtp_pass;
-
$mail->Username = $your_smtp_user;
-
$mail->Subject = "$your_website feedback";
-
$mail->SMTPAuth = "true";
-
-
$mail->Body = $response;
-
$mail->AddAddress($your_email,"$your_website admin");
-
$mail->AddReplyTo($email,$name);
-
-
echo "<p>Thanks for your feedback, <em>$name</em>! We will contact you soon!</p>";
-
if (!$mail->Send()) {
-
echo "<p>There was an error in sending mail, please try again at a later time</p>";
-
}
-
-
$mail->ClearAddresses();
-
$mail->ClearAttachments();
Note : Please change the SMTP server setting to your own server.
Although PHPMailer code seems a bit longer - it is much more readable and cleaner to write than the default mail() code.
Example code
Download example Contact Form code that uses PHPMailer : plaincf.zip (83KB)
Tags: php, phpmailer, smtp, mail, contact form, spammers, injection, emails, email
Posted in Uncategorized |








May 9th, 2007 at 6:11 pm
[...] This is an example of an enhanced contact form previously previously featured here and here [...]
September 13th, 2007 at 1:41 am
THANK YOU VERY MUCH !!!!!! IT WORKS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Like how we say in my country:
THANK YOU TEACHER!!!!!!!!!!!!
January 21st, 2008 at 7:52 pm
Thankyou this WORKS well just what I am looking for. It gets past that anoying mail error in the windows servers…Warning: mail() [function.mail]: Failed to connect to mailserver at “localhost” ERROR NO MORE :)