Besides using PHP's mail() function, there are a few other tools you can use to send mail from a PHP script. In this article, we'll show you how you can use PHPMailer to to send email from within PHP.

When sending email from PHPMailer, you will be sending email from an actual email address. If you don't already have an email address setup specifically for sending email, please setup an email address now. In the example below, we created the email address send_from_PHPMailer@bradm.inmotionhosting.com with "password" as the password.

Download the PHPMailer script

First, download PHPMailer using the direct link below:

PHPMailer_5.2.0.zip

After you have downloaded the file, unzip and extract it to your public_html. After unzipping the file we have public_html/PHPMailer_5.2.0. Next you will need to edit your web pages to use the PHPMailer code.

Add the HTML form to your page

Generally, your setup would include a form being sent to a PHP script for processing. In this case, there is a basic HTML file, contact_us.html, that makes up a feedback form. You will need to set the action of your form to "email.php" for the PHP script to process. Below is the code you need for the form in your page.

<form method="post" action="email.php">
  Email: <input name="email" id="email" type="text" /><br />

  Message:<br />
  <textarea name="message" id="message" rows="15" cols="40"></textarea><br />

  <input type="submit" value="Submit" />
</form>

Add the PHP mail() function code

When the form is filled out, the information is passed over to "email.php"', which currently uses PHP's mail() function to send the message. Below is the PHP code that sends the email from the server.

<?php

  $email = $_REQUEST['email'] ;
  $message = $_REQUEST['message'] ;

  // here we use the php mail function
  // to send an email to:
  // you@yourdomain.com
  mail( "bradm@inmotiontesting.com", "Feedback Form Results",$message, "From: $email" );
?>

Add the PHPMailer code to your site

Because we are using the PHPMailer instead of the generic php mail function, we'll begin to update our "email.php" file. If you look in your PHPMailer folder you'll see a README file that includes sample PHP code. The sample PHP code should look like below:

<?php
require("class.PHPMailer.php");

$mail = new PHPMailer();

$mail->IsSMTP();                                      // set mailer to use SMTP
$mail->Host = "smtp1.example.com;smtp2.example.com";  // specify main and backup server
$mail->SMTPAuth = true;     // turn on SMTP authentication
$mail->Username = "jswan";  // SMTP username
$mail->Password = "secret"; // SMTP password

$mail->From = "from@example.com";
$mail->FromName = "Mailer";
$mail->AddAddress("josh@example.net", "Josh Adams");
$mail->AddAddress("ellen@example.com");                  // name is optional
$mail->AddReplyTo("info@example.com", "Information");

$mail->WordWrap = 50;                                 // set word wrap to 50 characters
$mail->AddAttachment("/var/tmp/file.tar.gz");         // add attachments
$mail->AddAttachment("/tmp/image.jpg", "new.jpg");    // optional name
$mail->IsHTML(true);                                  // set email format to HTML

$mail->Subject = "Here is the subject";
$mail->Body    = "This is the HTML message body <b>in bold!</b>";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";

if(!$mail->Send())
{
   echo "Message could not be sent. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
}

echo "Message has been sent";
?>

The great thing about this example is that it includes comments, which explain what most of the code does.

Final Configuration of the PHPMailer code

We've updated the sample code to work with our initial html contact form (first code example on this page). We updated the code to include additional comments, and the final code we used is below:

<?php

// $email and $message are the data that is being
// posted to this page from our html contact form
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;

// When we unzipped PHPMailer, it unzipped to
// public_html/PHPMailer_5.2.0
require("lib/PHPMailer/PHPMailerAutoload.php");

$mail = new PHPMailer();

// set mailer to use SMTP
$mail->IsSMTP();

// As this email.php script lives on the same server as our email server
// we are setting the HOST to localhost
$mail->Host = "localhost";  // specify main and backup server

$mail->SMTPAuth = true;     // turn on SMTP authentication

// When sending email using PHPMailer, you need to send from a valid email address
// In this case, we setup a test email account with the following credentials:
// email: send_from_PHPMailer@bradm.inmotiontesting.com
// pass: password
$mail->Username = "send_from_PHPMailer@bradm.inmotiontesting.com";  // SMTP username
$mail->Password = "password"; // SMTP password

// $email is the user's email address the specified
// on our contact us page. We set this variable at
// the top of this page with:
// $email = $_REQUEST['email'] ;
$mail->From = $email;

// below we want to set the email address we will be sending our email to.
$mail->AddAddress("bradm@inmotiontesting.com", "Brad Markle");

// set word wrap to 50 characters
$mail->WordWrap = 50;
// set email format to HTML
$mail->IsHTML(true);

$mail->Subject = "You have received feedback from your website!";

// $message is the user's message they typed in
// on our contact us page. We set this variable at
// the top of this page with:
// $message = $_REQUEST['message'] ;
$mail->Body    = $message;
$mail->AltBody = $message;

if(!$mail->Send())
{
   echo "Message could not be sent. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
}

echo "Message has been sent";
?>

So in the test the user first visits contact_us.html. When they fill in their email address and comment, the information is posted to email.php. email.php calls PHPMailer, and then sends us the data that the user submitted.

Note that PHPMailer is very flexible and has more features than described here. For a listing of the optional variables that you can add, you should read the documentation:

http://PHPMailer.sourceforge.net/docs/

Did you find this article helpful?

We value your feedback!

Why was this article not helpful? (Check all that apply)
The article is too difficult or too technical to follow.
There is a step or detail missing from the instructions.
The information is incorrect or out-of-date.
It does not resolve the question/problem I have.
How did you find this article?
Please tell us how we can improve our Support Center:
Email Address
Optional, but our team may contact you for more information.
Like this Article?

Comments

Post a comment
2012-05-02 9:38 am
This was perfectly presented! Thanks, Brad!
n/a Points
2014-03-05 1:00 am

After module installation I can't get the PHPMailer to send any email; always end up with the SMTP -> ERROR: Failed to connect to server: Connection refused (111)can you please help me out from this??

Staff
4,112 Points
2014-03-05 9:23 am
Within your code, be sure that you have properly configured all of the settings such as the SMTP user and password to reflect a valid user that you have created.
n/a Points
2014-03-19 8:55 am

Hi, I just got off a chat session with Nick W.

I am having an issue getting Drupal 7 module PHPMailer working. It used to work before I moved to IMH. We ran through setup, and I ran the configuration test. The connection went through fine, and all reponses were positive, until the actual data was sent.

Following is the end of the communication.

SMTP -> get_lines(): $data was ""SMTP -> get_lines(): $str is "354 Enter message, ending with "." on a line by itself "SMTP -> get_lines(): $data is "354 Enter message, ending with "." on a line by itself "SMTP -> FROM SERVER:354 Enter message, ending with "." on a line by itselfCLIENT -> SMTP: Date: Wed, 19 Mar 2014 08:31:14 -0400CLIENT -> SMTP: Return-Path:CLIENT -> SMTP: To: mbrett5062@hotmail.comCLIENT -> SMTP: From: Log PowerCLIENT -> SMTP: Reply-To: mhooper@logpower.comCLIENT -> SMTP: Subject: PHPMailer test e-mailCLIENT -> SMTP: Message-ID: <731753829fd5d5027d27dbefccda3bd7@logpower.com>CLIENT -> SMTP: X-Priority: 3CLIENT -> SMTP: X-Mailer: PHPMailer 5.2.5 (https://github.com/Synchro/PHPMailer/)CLIENT -> SMTP: X-Mailer: DrupalCLIENT -> SMTP: MIME-Version: 1.0CLIENT -> SMTP: Content-Transfer-Encoding: 8BitCLIENT -> SMTP: Content-Type: text/plain; format=flowed; delsp=yes; charset=UTF-8CLIENT -> SMTP:CLIENT -> SMTP: Your site is properly configured to send e-mails using the *PHPMailer*CLIENT -> SMTP: library.CLIENT -> SMTP:CLIENT -> SMTP: .SMTP -> get_lines(): $data was ""SMTP -> get_lines(): $str is ""SMTP -> get_lines(): $data is ""SMTP -> get_lines(): timed-out (10 seconds)SMTP -> FROM SERVER:SMTP -> ERROR: DATA not accepted from server:

Staff
4,112 Points
2014-03-19 9:10 am
Your error appears to be related to the connection to the defined SMTP host timing out. Within your script, what do you have defined as the host?
n/a Points
2014-03-19 9:18 am

You can ignore my previous comment. Although the communication was saying server not accepting data, the mail was sent. Everything appears to be working on the site now.

Thanks anyway.

n/a Points
2014-03-25 8:58 am

I need help please, I get the following alert when I try to send an email in the same code

SMTP Error: Could not connect to SMTP host. Message could not be sent.

Mailer Error: SMTP Error: Could not connect to SMTP host.

<?php

require("/home/drinkinc/public_html/testmail/PHPMailer_v5.1/class.phpmailer.php");

$mail = new PHPMailer();

$mail->IsSMTP(); // set mailer to use SMTP

$mail->Host = "locaalhost"; // specify main and backup server

$mail->SMTPAuth = true; // turn on SMTP authentication

$mail->Username = "user@example.com"; // SMTP username

$mail->Password = "password"; // SMTP password

$mail->From = "user@example.com";

$mail->FromName = "User";

$mail->AddAddress($_POST['sender_email']); // name is optional

$mail->WordWrap = 50; // set word wrap to 50 characters

$mail->IsHTML(true); // set email format to HTML

$mail->Subject = "Here is the subject";

$mail->Body = "This is the HTML message body <b>in bold!</b>";

$mail->AltBody = "This is the body in plain text for non-HTML mail clients";

if(!$mail->Send())

{

echo "Message could not be sent. <p>";

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

exit;

}

echo "Message has been sent";

?>

Mailer Error: SMTP Error: Could not connect to SMTP host.

Staff
5,603 Points
2014-03-25 9:36 am
Hello dor,

I had to modify the code in your comment before allowing it to go public as you had your email information typed in. But it looks like more than likely the problem you're encountering is coming from this line:

$mail->Host = "locaalhost";



It looks like you have an extra a in the server name, as it it should read:

$mail->Host = "localhost";



A PHP script should understand that when you use localhost in your code you are referring to connecting to the same server the script is running on. But with it mistyped, it would literally try to go out and find a server named locaalhost on the Internet but would be unable to connect to it.

Please let us know if correcting that line fixes this problem for you.

- Jacob
n/a Points
2014-04-11 7:59 am

Please Help, I get this alert after execution.

SMTP Error: Could not connect to SMTP host. Message could not be sent.

Mailer Error: SMTP Error: Could not connect to SMTP host.

<?php

 

$email = $_REQUEST['email'] ;

$message = $_REQUEST['message'] ;

require("PHPMailer/class.phpmailer.php");

$mail = new PHPMailer();

$mail->IsSMTP();

$mail->Host = "localhost";  

$mail->SMTPAuth = true;     

$mail->Username = "mysite@gmail.com";  // SMTP username

$mail->Password = "password"; // SMTP password

$mail->From = $email;

$mail->AddAddress($email, "MySite");

$mail->WordWrap = 50;// set word wrap to 50 characters

$mail->IsHTML(true);// set email format to HTML

$mail->Subject = "You have received feedback from your website!";

$mail->Body    = $message;

$mail->AltBody = $message;

if(!$mail->Send())

{

   echo "Message could not be sent. <p>";

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

   exit;

}

echo "Message has been sent";

?>

Staff
5,444 Points
2014-04-11 10:57 am
Hello Aman,

Thank you for your question. In your script are you updating the following lines with the correct information?

$mail->Host = "localhost";
If you are running the script from a local server, localhost is correct; if you are running the script on a remote server, enter the correct hostname. For example: remote-domain.com

$mail->Username = "mysite@gmail.com"; // SMTP username
Make sure you are putting a valid SMTP username here.

$mail->Password = "password"; // SMTP password
Make sure you are putting a valid SMTP password here, for the email address.

If you have any further questions, feel free to post them below.
Thank you,

-John-Paul
n/a Points
2014-04-16 3:47 am

Hello John-Paul,

Thanx for your suggestions but these all things are correct in my code. I have put valid gmail Id and its password and i am using this code on Localhost . So i have set firstly 

$mail->Host = "localhost"; 

and thn 

$mail->Host = "smtp.gmail.com";

but error message remains same that is:

SMTP Error: Could not connect to SMTP host. Message could not be sent.

Mailer Error: SMTP Error: Could not connect to SMTP host.

So what can i do ?

 

Thanks & Regards,

Aman

Staff
5,603 Points
2014-04-16 12:15 pm
Hello Aman,

If you're using Gmail for your mail server then you're going to need to set things up a bit differently.

I'd try these settings:

$mail->SMTPAuth   = true; 
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;


Please let us know if you're still having issues connecting.

- Jacob

Post a Comment

Name:
Email Address:
Comment:
Are you a bot?
Submit

Please note: Your name and comment will be displayed, but we will not show your email address.

Write New!
Do you want to publish a tutorial to our support center?

News / Announcements

SSL Certficate Warnings
Updated 2014-04-14 11:34 am EST
Hits: 2231
Heartbleed 0-day OpenSSL security bug
Updated 2014-04-14 04:43 pm EST
Hits: 5662

Related Questions

Here are a few questions related to this article that our customers have asked:
PHPMail - Warning: Wrong datatype... /class.phpmailer.php
Would you like to ask a question about this page? If so, click the button below!
Ask a Question

Need more Help?

Search

Ask the Community!

Get help with your questions from our community of like-minded hosting users and InMotion Hosting Staff.

Current Customers

Chat: Click to Chat Now E-mail: support@InMotionHosting.com
Call: 888-321-HOST (4678) Ticket: Submit a Support Ticket

Not a Customer?

Get web hosting from a company that is here to help. Sign up today!