Home > PHP/MySQL Programming > Sending e-mail from PHP using mail()

Sending e-mail from PHP using mail()

April 11th, 2007

A very simple tutorial to send an e-mail directly from a PHP script using the built-in mail() function. Great for processing forms or just to debug an application.

For sending more advanced e-mail, including HTML, we recommend the PHPMailer class, however, for sending a basic e-mail the easy way, we use this simple function provided by PHP.

The mail() function contains the following elements:

  • Recipient e-mail address
  • E-mail subject
  • E-mail message
  • Optional extras (from or reply-to e-mail address)

A basic email

The recipient of the e-mail can include just the e-mail address:

#recipient e-mail
$recipient = "name@domain.com";

You can also include a recipient name with the e-mail address using the following format:

#recipient name and e-mail
$recipient = "Name <name@domain.com>";

Separate multiple recipients with a comma. To insert line breaks into the e-mail message add “n” to insert a line break.

#e-mail subject
$subject = "Test E-mail";
#e-mail message
$message = "Hello,nnThis is a test e-mail";

Now we use the mail() function to send the e-mail.

#send the e-mail
mail($recipient, $subject, $message);

A more advanced e-mail

To insert additional information including the from and reply-to e-mail addresses we use headers.

#insert from and reply-to addresses
$header = "From: name@domain.com rn Reply-To: name@domain.com";
#send the e-mail
mail($recipient, $subject, $message, $header);

All done!

That’s all the code required to send an e-mail using the mail() function. For more information on any of the code featured above visit www.php.net for the online manual.

For more information on web development please contact us on +44(0)1202 315285 or info@acmultimedia.co.uk. Learn more about AC Multimedia.
Bookmark and Share

PHP/MySQL Programming

  1. Archive
    March 25th, 2009 at 16:33 | #1

    I’d like to point to the security risks of using the php mail() functions when using user submitted data. You have to filter the user input to prevent automated SPAM runs being send trough the script. If a user can add additional BCC: adresses in the header, an automated (hackers) script can send e-mails to thousands of other users.

  2. Archive
    March 25th, 2009 at 16:33 | #2

    I am also using the X-Mailer, MIME-Version, Content-Type and Content-Transfer-Encoding within the header. It’s because your email may be identified as spam if these elements are missing.

  3. Archive
    March 25th, 2009 at 16:33 | #3

    I tried by myself also….but sometimes…it showz error…..hope with the helps of this article will resolve the problem….thanks !!

  1. No trackbacks yet.