06/21/2011

How To Send Email In PHP

by Cyle
Categories: php
Tags: , ,
Comments: 1 Comment

Sending an email with PHP is extremely easy with the mail() function. All it takes is the basics to get started, and you can always do more later. To send a basic email we need the recipient’s email address, a subject, and the body of the message. See the example below:

1
2
3
4
5
6
7
8
9
10
<?php
$to = "reciever@example.com";
$subject = "Hey Friend";
$body = "Hello friend,\n\nHow's it going?";  // \n is a new line
if (mail($to, $subject, $body)) {
   echo "Message successfully sent!";
  } else {
   echo "Message delivery not successful";
  }
?>

The above email has an if/else statement stating whether or not the email was sent successfully. The if/else statement is not needed to send the email though just by using mail($to, $subject, $body). You can add multiple email addresses, just separate them with a comma ($to = "reciever1@example.com , reciever2@example.com";).

That’s all there is to it! Easy, huh? You can get a lot more advanced with email validation, spam protection, custom from field, etc. I’ll add a couple easy advancements below.

Email Validation

Email addresses can be difficult to type and usually look correct when something is missing or actually incorrect. Luckily for us PHP 5 and later came out with an email validation function that makes this extremely easy. In the next example we are going to add email validation to our first example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
$to = "reciever@example.com";
$subject = "Hey Friend";
$body = "Hello friend,\n\nHow's it going?";
 
if (filter_var($to, FILTER_VALIDATE_EMAIL)) {
  // The email address is valid and send email
  if (mail($to, $subject, $body)) {
   	echo "Message successfully sent!";
  	} else {
   	echo "Message delivery not successful";
  }
} else {
  // The email address is not valid
  echo "Email address is not valid";
}
?>

Changing The From, Cc, Reply Fields

If you expect to get a response or reply to the email you are sending with PHP, you probably want to include a “from” or “reply to” email address. You can do that and some more by editing the header argument in the mail() function. Let’s take our first example, but add a from and a reply to field:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$to = "reciever@example.com";
$subject = "Hey Friend";
$body = "Hello friend,\n\nHow's it going?";
$header = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n";
if (mail($to, $subject, $body, $header)) {
   echo "Message successfully sent!";
  } else {
   echo "Message delivery not successful";
  }
?>

Above we added the from field and reply to field of the email. Make sure it is added to the mail() function as well. \r\n is required at the end of each header field. If there is only one then it is not needed, but since we have two, it is.

Prevent Spamming

I highly recommend you do something to prevent spammers from using your email script to spam people. I would use CAPTCHA to prevent spammers from using it. It is an image verification script. Your website could be marked as spam if a spammer is using your website to send mass emails to a lot of people, so I think this is a must!

Cleaning It Up

Some email addresses make no sense at all (bigboy11927@aol.com) and the receiver may not recognize who the email is from. This is why it is also important to clean up your email script a bit and add descriptions to your To and From fields. This final example includes the basic script (cleaned up), email validation, and custom headers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
$to = "John Doe <reciever1@example.com> , Jane Doe <reciever2@example.com>";
$subject = "Hey Friend";
$body = "Hello friend,\n\nHow's it going?";
$header = 'From: Webmaster <webmaster@example.com>' . "\r\n" .
    'Reply-To: Webmaster <webmaster@example.com>';
 
if (filter_var($to, FILTER_VALIDATE_EMAIL)) {
  // The email address is valid and send email
  if (mail($to, $subject, $body, $header)) {
   	echo "Message successfully sent!";
  	} else {
   	echo "Message delivery not successful";
  }
} else {
  // The email address is not valid
  echo "Email address is not valid";
}
?>

That’s it! Now you know how to send an email using PHP!!

A Practical Example

Emailing from a website can be very useful. It is mostly used on “contact” pages, but I like to use it on my custom 404 error pages along with an apology for missing a page. This way I instantly get an email when a user visits a missing page. It helps me to resolve it much faster. The example below uses global $_SERVER elements. Read my post on PHP Global Server Variables for more information.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
$to = "Myself <me@mywebsite.com>";
$subject = "Page Error";
$body = "
Error Message:\n\n
Request URL: ".$_SERVER['REQUEST_URI']."\n
Redirect URL: ".$_SERVER['REDIRECT_URL']."\n
Time: ".strftime("%d/%b/%Y:%T")."\n
Referring URL: ".$_SERVER['HTTP_REFERER']."\n
Visitor's IP:".$_SERVER['REMOTE_ADDR']."\n
Remote Host:".$_SERVER['REMOT_HOST']."\n
Server Name:".$_SERVER['HTTP_HOST']."\n
Visitor's Browser:".$_SERVER['HTTP_USER_AGENT']."\n
Redirect Status:".$_SERVER['REDIRECT_STATUS']."\n
";
 
$header = 'From: Auto Error Emailer <error@mywebsite.com>';
 
if (filter_var($to, FILTER_VALIDATE_EMAIL)) {
  // The email address is valid and send email
  if (mail($to, $subject, $body, $header)) {
   	echo "Message successfully sent!";
  	} else {
   	echo "Message delivery not successful";
  }
} else {
  // The email address is not valid
  echo "Email address is not valid";
}
?>

The above would send an email with all the necessary information I should need to fix the missing page.


1 Comment »

  1. Wm Sideman says:

    Great post! This is by far one of my favorite post you have done. Bravo!

Leave a Reply

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



user-avatar
Today is Monday
06/26/2017