Send an email from PHP

It is common now for developers to use email as a means of communicating with users from the web site. There are many reasons that you might want to do this including:

  • Confirmation of user action
  • Password reset
  • Send error logs to site administrator

Before you start to configure your PHP scripts to send email, you will first need to know some configuration settings for your email system. The following information is required:

  • Name or IP address of SMTP server
  • Email address of recipient

The rest of the information you can fill in from your code. Now you are all set to send automated emails from your website. The easiest way is to use the mail() function. This example will send a basic email:

{code type=php}
$to = “”;
$subject = “Email Subject!”;
$bodytext = “This is a test!!\n\n”;
If (mail($to, $subject, $bodytext)) {
echo(“Send Ok!”);
} else echo(“Message failed!”);

That will work great, but you might want to cut down the errors due to typing mistakes or people just putting in rubbish email addresses. The easiest way to do this is to use FILTER_VALIDATE_EMAIL. This example will validate an email address taken that is entered on a web form:
{code type=php}
$email_address = filter_input(INPUT_GET, ’email’, FILTER_VALIDATE_EMAIL);
if (!$email_address) {
// The email address is not valid

The one problem with this approach is that it does not work with SMTP authentication. If your email system uses this then you will have to try a more comprehensive email solution like the Pear Mail package.


One Response

Leave a Reply

Your email address will not be published.

More Posts

How to use PHP Type Declarations

PHP has developed into a more strictly typed language in recent years. Type Declarations help with that and are a fairly new addition to PHP,


If you have come to JavaScript from a background in Java or C, then you will like the variation on the for loop. It is

Context Object Manipulation

One of the key concepts of JavaScript is the keyword this, which signifies the JavaScript context object. If you write an inner function, you can access

Polymorphic Functions

It is possible to define multiple functions with the same name in JavaScript, and the last one of those that you define will be the