PHP TutorialsWeb Developer

Send HTML email with php from localhost with SendMail

Written by:

Sending emails from your PHP code is a must for most larger web operations. Sometimes you just need a simple email with a simple body, sometimes you want a custom HTML email with custom CSS and styling for a marketing campaign. Well we can do it all. We can even send those HTML emails using php from our localhost.

Download the FREE SOURCE CODE for this script to send HTML emails with php: Download Source Code

Configure php to use SendMail

First you will need to configure our localhost php server to use the SendMail program to handle the email processing. So open up the php.ini file in your favorite text editor. You can usually find the php.ini file inside of the “php” folder in your web server directory (e.g. C:\xampp\php\php.ini). Scroll through the php.ini file looking for the “mail function”. This is the location of all of the email configuration information.

The php.ini file is the master configuration file for php. It contains all the global settings for the php server. Generally, most people never have a need to edit this file or change from the default configuration. There are a few instances that come to mind where you might need to edit the file like configuring your email server, adjusting file upload limits, or some other pretty uncommon things.

Update the “sendmail_path” to be the correct path location to your email handler program. The program is likely to be in the same locations listed below for Windows and Linux respectively, but it may be different.

For Windows:

sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

For Linux:

sendmail_path = "/usr/lib/sendmail -t"

You will note that their is a “-t” option at the end of the path. This option tells the SendMail program to look in the headers of the email for the addresses of the email recipients. You can read more about it here if you want, but basically it is a must have setting.

Configure the SMTP server connection

Next you will need to configure SendMail to connect to a SMTP server (aka mail server). You can either use the SMTP settings provided by your web host (if you have one) or you can use the ones provided by your normal email provider (e.g. Gmail, Yahoo, Hotmail, etc). For this example, I will use Gmail settings.

Open the sendmail.ini configuration file from the sendmail directory on your web server (e.g. C:\xampp\sendmail\sendmail.ini). Update the following settings with your own SMTP connection information:

smtp_server=smtp.gmail.com
smtp_port=465
smtp_ssl=auto
auth_username=GMAIL_USERNAME@gmail.com
auth_password=GMAIL_PASSWORD
error_logfile=error.log

Note: You may need to scroll around a bit to find all of the settings since the default configuration file typically has lots of comments in it to help you learn what each of the settings are for.

Check this out:  Make a Simple Search Engine with PHP (open source download)

Note: Be sure to correctly enter your username and password. If either is incorrect, you will not be able to actually send any emails. Which would be quite counter-productive.

After saving your new settings, restart the Apache web server. This will force the server to reload the new SendMail configuration.

Sending basic emails with php

Using the php mail() function, we can start to code out a basic email to send. Create a new php script and open it for editing.

The mail() function normally takes 4 total parameters each of which we will put into a separate variable for ease of editing: e.g. mail($to, $subject, $message, $headers );

  • to – the email address you are sending the email to (aka the recipient). This can be either one single email address or can be a list of emails, each separated by a comma. (e.g. “hello@nickfrosty.me, nick@nickfrosty.me”)
  • subject – you guessed it, the subject line of the email
  • message – the body of the message you are sending. This can also include line breaks, but only if they are properly formatted as a “\n” in the variable (this will make more sense in the example below)
  • headers – this specially formatted variable is what the email server will look at form some select information about the email being sent. Normally it will just include the “from” email address (aka the email address sending the email).

Send simple emails with php

Let’s take a look at the basic code in action to send our first email:

<?php

	$headers = "From: no-reply@heytuts.com\r\n";
	$to = "you@hyoursite.com";
	$subject = "Sending a basic email with php";
	$message = "Checkout this super simple script to send a basic text email!";

	if ( mail($to, $subject, $message, $headers) )
		echo 'Success!';
	else
		echo 'UNSUCCESSFUL...';

?>

The code to pay close attention to:

  • $headers – this variable has the “From” header stored in it. Notice how the “From” starts with a capital letter? That is very important. If this header doesn’t start with a capital, the mail() function may fail to send the email or the recipient may never get it.
  • You will also notice the “\r\n” in the headers. These are called escape characters. These specific ones are like syntax formatting the headers properly so that the email protocols can properly interpret all of the lines of the email’s header. Coding is all about the specific syntax!
  • the mail() function – this function is wrapped inside of an if statement, this means that in our code we can determine if the function is successful when it runs. For this example, I am just giving a simple text output. You can easily change that to any elaborate code you want to execute upon success or failure of the email to send. Your choice!
Check this out:  Fix PHP executable not found error in VS Code

That’s it! That is all the code you need to send a simple and quick basic text email to someone. But let’s look at another way to send a little bit more complicated email.

Multiple Recipients and New Lines

<?php

	$headers = "From: nick@heytuts.com\r\n";

	$to = "bob@yoursite.com, demo@yoursite.com";
	$subject = "Sending Emails From Localhost";
	$message = "Sending emails from a localhost home server?\n\nEven send custom multi line emails? Tell me more!";

	if ( mail($to, $subject, $message, $headers) )
		echo 'Success!';
	else
		echo 'UNSUCCESSFUL...';

?>

The code to pay attention to and what’s different from the last example:

  • $to – notice how the two message now has two email addresses listed in it, each separated by a comma. You can have almost as many email addresses as you would like in the $to parameter, but as you get more and more recipients the email script code will take longer and longer to execute (which may lead to the page timing out and the emails never actually sending)
  • $message – this message variable has been specially crafted to have multiple line breaks (aka new lines) in the body of the email. To get these new line breaks in a simple text email, just add the “\n” (that’s a forward slash followed by the n character, no space between them). You can even stack them together like I did to give you some extra space.

Once you get into having more complicated email bodies, the message can get fairly elaborate. Especially if you get particular about your formatting. What I like to do is make each new line of email body text into a new line in my php code. This makes the code a little cleaner and easier to edit in the future. Like this:

<?php

	$message = "This is the first line of my text email\n\n";
	$message .= "adding new lines\n";
	$message .= "makes it all look much cleaner!";

?>

Once you get into having more complicated email bodies, the message can get fairly elaborate. Especially if you get particular about your formatting. What I like to do is make each new line of email body text into a new line in my php code. This makes the code a little cleaner and easier to edit in the future. Like this:

Check this out:  Download Windows 10 Spotlight Images

Failing to send emails and the error.log file

How we have setup our email script is to give us a simple success message if and when the email functions successfully sends the email. Which is great! Knowing that the email sent to script out any other functions you want php to do is great. But what about when the email does not send? How do you find out why to troubleshoot and adjust your code? That’s with the error.log file. If you take a look at the sendmail.ini file we configured earlier, there is an error log file name listed. This simple text log will have any messages associated with your email script.

Each line will give you a date and time stamp, followed by the error message itself:

19/05/20 21:42:52 : <1.0@>: domain missing or malformed

Here is a short breakdown of the different error messages you may get:

  • “domain missing or malformed” – this error message may be given if you headers are not properly formatted, like missing a “/r/n”. So be sure to double check your headers for any typos.
  • “Invalid recipient email@yoursite.com” or “No valid recipients were found” – this is likely due to entering an email address that does not exist. Either as on of the recipients or the sender. So be sure to double check your spelling.

Now that you can send simple emails from localhost, enjoy sending emails to the masses using your new php script skills.

Download the FREE SOURCE CODE for this script to send HTML emails with php: Download Source Code

One Reply to “Send HTML email with php from localhost with SendMail”

  1. […] are hosting your website on a local web server, or just using a localhost web server, then you can configure that server to send the emails. Using the SendMail application and XAMPP, you can setup your localhost web server to send those […]

Leave a Reply

%d bloggers like this: