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.

Similar Posts

One Comment

Leave a Reply

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