Send an email from PHP

Last Updated on: February 25, 2023

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

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

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

  • Name or IP address of the SMTP server
  • Email address of the 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:

$to = “target@recipient.org”;
$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 reduce 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:

$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.


Get notified of new posts:


Similar Posts

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *