Send an email from PHP

by jeremyjones on March 9, 2011

  • Share
  • CevherShare
  • Share

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:

<?php
$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 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:

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

Leave a Comment

Previous post:

Next post: