PHP mail() overview

 

Overview

This article is an overview of PHP mail and how you can use it at DreamHost.

Background

Websites built on PHP can take advantage of the PHP mail function which creates the ability to send email directly from your website. PHP is available by default on all hosting plans, so there is nothing you need to enable to use the PHP mail function.

PHP mail examples

This section provides examples of PHP mail scripts and how SMTP authentication should be used when sending email from a web server.

Email Header Injection

Never use form input (such as names or email addresses) in the PHP mail() command. This can lead to mail header injection exploits which allow spammers to hijack your email forms. See the following pages for further information and how to prevent these attacks.

Creating an email file

To use PHP mail, log into your website and create a file named something like phpmail.php. Add the following code to create a simple PHP mail form.

<?php
//sending email with the php mail()
mail('user@example.com', 'Subject Line Here', 'Body of Message Here', 'From: admin@example.com');
?>

Make sure to change the FROM address to an email on your site's domain. For example, if your site is example.com, the FROM address should be something like admin@example.com. This is to avoid any issues with DreamHost's Sender Domain Policy.

When you visit this page in a browser, it appears as a blank white page. But by visiting it, you invoke the PHP mail function to send an email to the address entered.

Enabling SMTP authentication

DreamHost strongly recommends using SMTP authentication when sending email using PHP mail(). See the following articles for full examples of how to send SMTP mail via a PHP script.

This allows you to send from any email address you like while avoiding any issues with DreamHost's Sender Domain Policy.

Advanced examples

Visit the PHP mail page for a list of examples and parameters you can use to customize your mail script. For example:

  • Message variables
  • Email headers
  • Combining with HTML

See also

Did this article answer your questions?

Article last updated PST.

Still not finding what you're looking for?