hostmysite.com

How do I use PHP mail to send emails from my website?


Please note: This support article is a guide for our Linux users only.

The following article explains how to use PHP mail to send emails. PHP mail makes use of the mail() function and sends the email based on the parameters specified.

Send a Simple Email Message

Below is a sample script you can utilize for PHP mail:

<?php
$to = 'user@domain.com';
$subject = 'the subject';
$from = 'email@domain.com';
$message = 'hello';

if(mail($to, $subject, $message, "From: $from"))
  echo "Mail sent";
else
  echo "Mail send failure - message not sent"; ?>

Email the Results of a Form

To send the results of a form as an email from your website you will need to first create the HTML form. Within the form you will need to set the action to the page containing your PHP mail code. For example:

<form action="phpmailform.php" method="post">

Next, you will need to create the PHP page specified in the action which will contain the PHP mail code.

Below is a sample script you can utilize for PHP mail:

<?php
$to = 'user@domain.com';
$subject = 'the subject';
$from = 'email@domain.com';
$message ='';

foreach($_POST as $name => $data)
{
  if(is_array($data))
  {
    foreach($data as $datum)
    $message .= $name . ": " . $datum . " \n";
  }
else
  $message .= $name . ": " . $data . " \n";
}

# Attempt to send email
if(mail($to, $subject, $message, "From: $from"))
  echo "Mail sent";
else
  echo "Mail send failure - message not sent";
?>

Sending HTML Emails

To send the body of the email as HTML include the follow lines of code:

$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

Replace the Attempt to send email section with the following:

# Attempt to send email
if(mail($to, $subject, $message, "$headers \r\n From: $from"))
  echo "Mail sent";
else
  echo "Mail send failure - message not sent";

Additional Support Topics

Search Support Articles