Using PHPMAILER in a Wordpress template to send a contact form using Gmail SMTP server
October 24, 2009This post’s title is a mouthful. It seems like there’s some Wordpress users out there that want to create their own contact form that can be embedded into a template file. Plug-ins like contactform7.com don’t support embedding in templates, so I created my own simple script. However, there were some obstacles when dealing with Wordpress.
After plugging in my code for the form on the Top Right Corner Contact Page, tests were starting to fail. Even though the same code worked on plenty of other sites, I discovered that Wordpress does some funny things with $_POST data. From what I read, Wordpress does some cleaning of the data automagically before it gets sent anywhere.
Besides that, I learned that the variable $_POST['name'] is reserved. So, if you’re using $_POST['name'] to store a person’s name, make sure you change it to something like $_POST['fullname'].
Gmail SMTP
Next obstacle. So for whatever reason, PHP’s mail() function wasn’t working for me. I decided to use the phpmailer class included with Wordpress located at /wp-includes/class.phpmailer.php. Some sample code for PHPMAILER is here.
Another problem is that our mail servers are hosted by Gmail. So, to send an email we need to have the right authorization and you need to connect through SSL. My contact page, which is a template, uses this code to send a message posted from the contact form:
include ('./path/to/wp-includes/class-phpmailer.php');
include ('./path/to/wp-includes/class-smtp.php');
$mail=new PHPMailer();
// Let PHPMailer use remote SMTP Server to send Email
$mail->IsSMTP();
// Set the charactor set. The default is 'UTF-8'
$mail->CharSet='UTF-8';
// Add an recipients. You can add more recipients
// by using this method repeatedly.
$mail->AddAddress($to);
// Set the body of the Email.
$mail->Body=$message;
// Set "From" segment of header.
$mail->From=$from;
$mail->AddReplyTo($from, $name);
// Set addresser's name
$mail->FromName=$name;
// Set the title
$mail->Subject=$subject;
// Set the SMTP server.
$mail->Host='smtp.gmail.com';
$mail->Port= 465;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username='xxxx@xxxx.com';
$mail->Password='xxxxx';
// Send Email.
$mail->Send();
The most important part for Gmail is to set these parameters:
// Set the SMTP server.
$mail->Host='smtp.gmail.com';
$mail->Port= 465; // Or 587
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username='xxxx@xxxx.com';
$mail->Password='xxxxx';
So there you have it. That little piece of the puzzle that keeps you up late at night. Leave any questions in the comments.


