• Sales: 1-800-961-2888
  • Support: 1-800-961-4454

How do I test PHP SMTP functionality?


You can test PHP SMTP functions with the following two examples. The first one is standard SMTP while the second one is SMTP with SSL.

We strongly recommend using an SMTP relay that requires authentication. Sending mail through unauthenticated SMTP servers (including the localhost relay on Cloud Sites) can result in delays or undelivered email due to stringent anti-spam filters.

Sending with PHP SMTP

You will only need to change the following variables:

  • $from
  • $to
  • $subject
  • $body
  • $host
  • $username
  • $password

The host, username, and password values will depend on the provider you're using to send your email.  If you have a legacy Sites email account or are using Rackspace Email the host would be "mail.emailsrvr.com" and the username would be your email address.  If you're using another service such as Mailgun or Gmail to send email, you'll need to fill in the SMTP server for that service. Mailgun server information can be accessed via your Mailgun control panel.

<?php
require_once "Mail.php";
 
$from = "Web Master <webmaster@example.com>";
$to = "Nobody <nobody@example.com>";
$subject = "Test email using PHP SMTP\r\n\r\n";
$body = "This is a test email message";
 
$host = "mail.emailsrvr.com";
$username = "webmaster@example.com";
$password = "yourPassword";
 
$headers = array ('From' => $from,
  'To' => $to,
  'Subject' => $subject);
$smtp = Mail::factory('smtp',
  array ('host' => $host,
    'auth' => true,
    'username' => $username,
    'password' => $password));
 
$mail = $smtp->send($to, $headers, $body);
 
if (PEAR::isError($mail)) {
  echo("<p>" . $mail->getMessage() . "</p>");
} else {
  echo("<p>Message successfully sent!</p>");
}
?>

Sending with PHP SMTP with SSL

You will only need to change the following variables:

  • $from
  • $to
  • $subject
  • $body
  • $host
  • $username
  • $password
 
<?php
require_once "Mail.php";
 
$from = "Web Master <webmaster@example.com>";
$to = "Nobody <nobody@example.com>";
$subject = "Test email using PHP SMTP with SSL\r\n\r\n";
$body = "This is a test email message";
 
$host = "ssl://secure.emailsrvr.com";
$port = "465";
$username = "webmaster@example.com";
$password = "yourPassword";
 
$headers = array ('From' => $from,
  'To' => $to,
  'Subject' => $subject);
$smtp = Mail::factory('smtp',
  array ('host' => $host,
    'port' => $port,
    'auth' => true,
    'username' => $username,
    'password' => $password));
 
$mail = $smtp->send($to, $headers, $body);
 
if (PEAR::isError($mail)) {
  echo("<p>" . $mail->getMessage() . "</p>");
} else {
  echo("<p>Message successfully sent!</p>");
}
?>

Note: Mail.php is a PEAR module and is installed on the server. It is included in the default include_path for PHP, so requiring it here will work by default without any additional effort on your part.

See Also



© 2011-2013 Rackspace US, Inc.

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License


See license specifics and DISCLAIMER

32 Comments

Hi, Can i use SMTP of different host in my host, so that there is no much server load.

For instance, if I take host as google.com and give my username and password, and Setup SMTP in my Hosting, So that when it sends an email, it doesn't bother my hosting.
It just Cleanly Pick up and Connect with google apps host and than starts sending my email.

Thanks

You should be able to change the script given to use a different value for "$host", "$username", and "$password" to point the script to another SMTP host. Just make sure you use Google's SMTP server along with the right username and password and it shouldn't have a problem.

What is the correct syntax for adding content type in the header? I have tried
$headers["Content-Type"] = "text/html; charset=iso-8859-1"; But doesnt work...

I'm not terribly well-versed in PHP, but you might check the header() function, as in:

header('Content-Type: text/html; charset=iso-8859-1');

Make sure you include any header() calls before the page delivers any output (before the html tag).

For more info you can check the manual page for header(): http://php.net/manual/en/function.header.php

Email attachments can be sent as well by using mail/mime.php as in this article.

http://pear.php.net/manual/en/package.mail.mail-mime.example.php

How to add cc and bcc in this script ?

I located a resource in the PHP manual that should clarify how this can be done. http://php.net/manual/en/function.mail.php. Based on this, you should be able to accomplish adding CC and BCC through "additional_headers".

I have a form which dependent on which enquiry type has to be forwarded to different emails. Currently using the above script I seem to be limited to using the $username as $to. If I do anything else I get an error email sent to the sender. Would I have to create and arrays for $username and
$password for each email address and use them depending on the enquiry type of the form.

As written, the "to" variable would only work as an email address. Similarly, "username" and "password" are only used to log into the SMTP server - you would only need to use a single value for each, since you likely are just using the one account on the SMTP server when sending.

I'm not certain how the PHP SMTP can handle multiple recipients with its built-in functions (you'd want to check the PHP documentation for that), but a simple workaround if it's a short list of recipients might be to just create an array of "to" addresses, then run a loop to cycle through the array and create an email to each one in turn.

I have set up postfix on the cloud server as detailed in the docs, but what username / password should I use in the PHP code to connect to the SMTP server? Is there another knowledgebase article that describes setting up the access to the SMTP server? (I couldn't find one searching for "SMTP")

The username you'd use would be one of the email addresses you've set up for Cloud Sites, and the password would be that account's password. If you haven't set up any email addresses yet, you can find instructions in [this article](http://www.rackspace.com/knowledge_center/index.php/How_do_I_create_an_email_account).

We'll look at updating this article to make that more clear. If you still have any problems definitely let us know.

Yes, it would be great if you could please add those instructions into the article itself; that would've saved me a lot of time, as I hadn't seen this comment until later. Thank you, Jered!

Gah, sorry for not updating this one - slipped through the cracks. I'll get it done now. Thanks for keeping me honest, David. ;) It's worth noting that we no longer offer email accounts for newer sites, but I'll make sure the explanation covers any mail service that allows SMTP connections (like Sendgrid or Gmail).

My mistake... I posted this in the wrong thread. I am trying to set up SMTP and email accounts on a Cloud *Server* not a Cloud *Site*.

Ah, I see. Are you using a local mail server on Linux to send the email? In that event, I suspect you can change the value of "auth" to "false" and leave out the username and password references. For more details on setting up a local mail server you can look for "postfix" and likely find the information you need for Linux.

For that matter, you could save a bit of trouble by signing up with SendGrid and sending mail through them (in which case, you'd use the username and password for their service). It's free for Rackspace Cloud users up to 40,000 emails a month. More details on that here:

http://www.rackspace.com/knowledge_center/sendgrid

Hi all,

I am using 2nd option of code and tried to send html format of email but it send junk code of html in the mail body. I have added below option in header but its not working at my end.
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

any suggestion what changes need to do to send html format mail.

There's a code example for sending HTML email on the documentation page for PHP Mail:

http://php.net/manual/en/function.mail.php

Hopefully that does the trick.

To send HTML mail in PHP, you need to use some additional headers. Below is the code to send HTML mail in PHP.

$to = “recipient@domain.com“;
$subject= “Subject of email”;
$message= “This is <h1>HTML</h1> mail.”;
$fromName = “Name of the sender”;
$fromEmail = “sender@domain.com“;

// To send HTML mail, the Content-type header must be set
$headers = “MIME-Version: 1.0? . “\r\n”;
$headers .= “Content-type: text/html; charset=iso-8859-1? . “\r\n”;

// Additional headers
$headers .=”From: $fromName <$fromEmail>”.”\r\n”;

//Mail function
mail($to, $subject, $message, $headers);

Source:
<a href="http://phphelp.co/2012/05/03/how-to-send-html-mail-in-php//">http://http://phphelp.co/2012/05/03/how-to-send-html-mail-in-php//</a>

OR

<a href="http://addr.pk/a1c4">http://http://addr.pk/a1c4</a>

Hi,

I am useing smtp. How add cc and cc in my code. Please help me.



<?php
include('SMTPconfig.php');
include('SMTPClass.php');

$to='webmaster@advenser.com';
$subject="Contact from Advenser.com";
$from="webmaster@advenser.com";
$fname=$_POST["txtFName"];
$lname=$_POST["txtLName"];
$com=$_POST["txtCompany"];
$web=$_POST["txtWebsite"];
$email=$_POST["txtEmail"];
$tel=$_POST["txtPhone"];
$adrs=$_POST["txtAddress"];
$msg=$_POST["txtComments"];
$hear=$_POST["txtHear"];
$body ="
First Name : $fname
Last Name : $lname
Company : $com
Website : $web
Email : $email
Telephone : $tel
Address : $adrs
Messages : $msg
How did you hear about us : $hear
";
$m="";
if($_POST["ans"]==7)
{
if(ereg("([0-9,a-z,A-Z]@[0-9,a-z,A-Z].[0-9,a-z,A-Z])",$email))
{
if($_POST["C"]=="Send")
{
$SMTPMail = new SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body);
$SMTPChat = $SMTPMail->SendMail();
if($SMTPMail==true)
$m="Mail sent Successfully";
else
$m="Sent Failed";
}
}
else
{
if($_POST["C"]=="Send")
{
$m="Invalid email address";
}
}
}
else
{
if($_POST["C"]=="Send")
{
$m="Invalid Answer";
}
}
?>

I'm afraid I'm not familiar with the PHP class you're using, and we can't provide that much support for coding in any event. The best I can suggest would be to go to the documentation for the class you're using - there should be information there about how to include cc and bcc, or how to set heders for the email.

If you use the Mail.php from the example above, to add cc or bcc you would modify the "headers" array to include an entry for "cc" and one for "bcc".

I tried using mail.php for cc & bcc but it seems, it do not support cc & bcc. Is there any way or any one know any working script (described properly) for sending cc & bcc in smtp mail, Please help..

In PHPMail, the cc and bcc values are treated as "additional headers". See this page for a description of how to set the additional headers, plus an example further down the page that adds cc and bcc headers:

http://php.net/manual/en/function.mail.php

<?php
require_once "Mail.php";

$from = "Mister Smith <mister@smith>";
$to = "Mister Smith<mister@smith.com>";
$cc = "Mister Brown <mister@brown.com>";
$recipients = $to.", ".$cc;

$subject = "Test subject";
$body = "My message body line 1" . "\r\n\r\n";
$body .= "My message body line2". "\r\n\r\n";

$host = "mail.emailsrvr.com";
$username = "xxxx@yourdomain.com";
$password = "xxxxxx";

$headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject, 'Cc' => $cc);

$smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => true, 'username' => $username, 'password' => $password));

$mail = $smtp->send($recipients, $headers, $body);
?>


Hope that helps someone.

For HTML email, just add the additional header information as described in a comment above.

Thank you ,the script is very helpfull

Hi I wonder if anyone can help - I am using the suggested code but the emails come through as to 'undisclosed recipients' and with no subject. Both of these variables are however included in the body of the email that comes through.

Here's the code I am using:

$host = "xxxxxxxxxxxxxxx";
$port = "465";
$user = "xxxxxxxxxxx";
$pass = "xxxxxxxxxxxxx";

$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);

$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $user,
'password' => $pass));

$mail = $smtp->send($to, $headers, $body);

I've checked the emails in in Outlook and webmail just to make sure it wasn't the email app - and the result is the same.

Thanks.

If that's your complete code, I don't see the values for the $from, $to, $subject and $body variables. I assume those are set earlier. You say that the "from" and "subject" are included in the body - is that by design, or is that something that's being added to the message that wasn't in your original "body" variable?

Also, have you tried a different mail server, to see if that changes the result? You can set up an account with Mailgun or Sendgrid that would allow low-volume mail sending, so it may be worth seeing if the result is the same with them.

Hi Jered,

thanks for the response.

Yes, the variables are defined earlier, I have tested each one and they are correct.

The fact that they are in the body is not by design. As a test I removed the middle line from:
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
and it removed the 'To' part from the body of the email.

I'm using the emailsrvr mail server so I'm guessing that shouldn't be the cause of it?

I may look at Mailgun or Sendgrid as I'm struggling to think what else I can check at this point, let me know if you spot anything.

Hi Jared,

I have managed to get this working using Mailgun, but this does have the downside that (unless you pay) you lose the ability to set the from variable as from your own domain.

Given that the mailserver I'm using is hosted by rackspace and the code I'm trying to get to work is also based on the rackspace code it would be good to know why I can't pass the subject variable - and why the to variable ends up being set to 'undisclosed recipients'.

Actually, for Mailgun, apply the promo code "mg4rackspace" to your Mailgun account. Since Rackspace bought Mailgun they've been offering a $19/month credit to Rackspace users through that promo code. That would let you use their Standard plan and get all the benefits thereby, including your own "From" domains. Sorry I didn't mention that sooner.

I do agree that if it works with Mailgun it should work with the Rackspace Email servers as well. I'll try to look into that further. It might be worth trying "smtp.emailsrvr.com" and port 587 to see if the non-ssl mail server behaves any differently, but only if you really want to use the Rackspace mail server with the code. If you have things working on Mailgun, no need to change to test that if you don't want to - I'll check with some folks on the backend to see if they can tell why this might be happening.

Hi Jered,

thanks for the response.

Yes, the variables are defined earlier, I have tested each one and they are correct.

The fact that they are in the body is not by design. As a test I removed the middle line from:
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
and it removed the 'To' part from the body of the email.

I'm using the emailsrvr mail server so I'm guessing that shouldn't be the cause of it?

I may look at Mailgun or Sendgrid as I'm struggling to think what else I can check at this point, let me know if you spot anything.

PS this is the 5th time I've tried to submit this message but it keeps throwing out an error.

how exactly do the test.i cannot understand

The code in the article is intended to be put into a file (like "test.php"), customized to use your values (like username and mail host), then run with the "php" command or accessed in a browser via a web server that can process PHP (like apache running mod_php). The idea is that you can confirm the functionality of your mail relay before working the code into a larger program.

Add new comment