Photo by Clark Young

Make your PHPMailer Work

Have you used


mail();

in your code for your contact form? And does it always work?

Well, this function does not always work.

“It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.” – php.net

So don’t expect that you will really receive the email using this function.

So what to use instead?

Use PHPMailer.

PHPMailer is a PHP plugin used to send an email from your contact form. And this is object-oriented. If you don’t know how to code in an object-oriented manner, don’t worry. You can still copy it and just study it later. It is very simple.

Download the PHPMailer plugin here. You can also look here for more examples.

Let’s  start!

In this program, I just want to receive the details the user entered when she submitted the form.

<section class="container">
<h1>Form Submission</h1>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label for="name">First Name</label>
<input type="text" id="name" name="name">
<label for="emailAdd">Email Address</label>
<input type="email" id="emailAdd" name="email">
<input name="submit" type="submit" value="Submit &raquo;">
</form>
</section>

I got here a simple form using HTML5 markup. I have a section with a class of container just to hold my form. My form has an action attribute with the value of this:

 <?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> 

for security purposes.

What is that?!

The function, htmlspecialchars(), converts special characters into html entities. And the $_SERVER[“PHP_SELF”] is a global variable that gives you the name of the currently executing script.

User input may contain anything. And to protect your form from hackers, those special characters will be converted so they can’t hack any of the data that is processing.

I use this if the PHP code that will perform the processing is in the same file of my form. It means that this same file will also process the data received by the form.

We required the PHPMailer file at the start of our PHP file, right?

I added this code just before my section that holds the form.


<?php
require_once('functions.php');
date_default_timezone_set('Etc/UTC');
require 'PHPMailer/PHPMailerAutoload.php';

$name = $email = $response = "";

if (isset($_POST["submit"])) {
$requiredFields = array("name", "email");
validatePresence($requiredFields);

$name = trim(stripslashes(htmlspecialchars($_POST["name"])));
$email = trim(stripslashes(htmlspecialchars($_POST["email"])));

if (isPresent($name)) {
isName($name);
}

if (isPresent($email)) {
isEmail($email);
}

if (has_header_injection($name)
||
has_header_injection($email)) {
die();
}
?>

The functions that you can see above are methods used to validate the user input from the form. Those functions such as validatePresence() are stored in another php file called ‘functions.php’.

I’ll discuss more on validating inputs in another blog post soon.

So if the user clicks on the submit button, my PHP code will validate those inputs. And if any of the functions got a wrong input then it will store an error message in my errors array.

Basically, that is the point.

If my array of errors is empty, then we shall proceed in processing our data.

<?php
if (empty($errors)) { 
$to = "gonzalesjoahna@gmail.com"; 
$subject = "$name sent you a message via your contact form"; 
$realMessage = "Name: $name\r\n"; 
$realMessage .= "Email: $email\r\n"; 
$realMessage .= "Message: \r\nAdd to mailing list."; 
$realMessage = wordwrap($realMessage, 72);
?>

I created variables here, $to, $subject and $realMessage.
1. Set the email address that is the recipient in the variable $to.

2. Write your compelling headline in the variable $subject.

3. Write the message in the variable $realMessage. You can see the function, wordwrap(). It wraps your message in the given number of characters. I like to wrap my message into 72 characters so it’ll also be backward compatible with older email services.

<?php
$mail = new PHPMailer; 
$mail->isSMTP(); 
$mail->SMTPDebug = 0;
$mail->Host = 'smtp.gmail.com'; 
$mail->Port = 587; 
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true; 
$mail->Username = "your_email_address_here"; 
$mail->Password = "your_password_here"; 
$mail->setFrom($email, ucfirst($name)); 
$mail->addAddress($to, 'name_of_the_recipient'); 
$mail->Subject = $subject; 
$mail->Body = $realMessage; 
if (!$mail->send()) { 
addMailError(); 
} else { 
$response = "Thank you for leaving a message!";
}
}
}
?>

So $mail = new PHPMailer declares a new instance or a new object of PHPMailer. You’re like getting another apple from the basket of apples with the same taste, nutrition and stuff. You have a new object and its methods.

The method, isSMTP(), if set to true will set mailer to use SMTP.

If SMTPDebug is set to 0, then the errors when you’re debugging will not appear.

The host is the SMTP server to be used. In my case, this is a gmail server.

The port is the TCP port to connect to while the SMTPSecure is to enable TLS encryption. And SMTPAuth enables SMTP authentication. If you enables these to true, then you’re going to need username and password.

The username and password here are the SMTP username and password. In this case, they are the details for my gmail account which is the recipient of the message.

The setFrom attribute is the email address and the name of the person who submitted the form.

The addAddress attribute is the recipient email address.

The subject is the subject. The body is the message you formed.

<?php
if (empty($response)) {
echo displayErrors();
} else {
echo $response;
}
?>

You can add this code just before the label of first name.

If the variable $response is empty, then this means that there are errors. It will display the array of errors just before the label of first name.

And if there are no errors and it sends, then the “Thank you” message will appear.

Okay, I’m getting bored here.

I usually just copy and paste code and see if it works. That’s why you can download the whole folder here (Take note: I’m using Bootstrap here). This is working for me. I can really receive the details entered by the user.

But if it does not work, change to:

<?php
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
?>

This will show the client and server error messages when something goes wrong in processing your data.

And change addMailError(); to

<?php
echo "Mailer Error: " . $mail->ErrorInfo;
?>

Read the output and I think you’ll identify what’s wrong. Either you totally get it or just search about it again in your favorite search engine. And try to solve it.

Good luck!

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s