Skip to content

How to Send Emails with PHP Mail() Function

  • by
php mail

Sendmail in PHP is possible with just single line of code. PHP contains built-in mail functions to send mail.

There are reasons why I am feeling embraced with this PHP feature. Because I write lot of code for sending mails regularly. PHP really saves our time with its built-ins.

Quick Example

<?php mail('recipient@domain.com', 'Mail Subject', 'Mail content');  ?>

n this tutorial, we will see how to add code to sendmail in PHP. We will see several examples in this to enrich the features with more support.

The below list examples we are going to see below. It will cover basic to full-fledged support to sendmail in PHP.

  1. Simple text mail with PHP mail().
  2. Send rich-text content via mail.
  3. Sendmail in PHP with attachments.
  4. Sendmail using PHPMailer with SMTP.

PHP mail()

Parameters

$recipient_email
One or more comma-separated value that is the target mail addresses. The sample format of the values are,

  • name@domain.com
  • Name <name@domain.com>
  • name@domain.com, name2.domain.com
  • Name <name@domain.com>, Name2 <name2@domain.com>

$subject
Mail subject.

$message
Mail content body. It uses \r\n for passing a multi-line text. It has a character limit of 70 for a line. It accepts various content types depends on the specification in the extra header.

$headers
This is an extra string or array append to the mail header. Use to pass the array of specifications like content-type, charset and more. It’s an optional parameter. It uses \r\n to append multiple headers. The header array contains key-value pair to specify header name and specification respectively.

$additional_params
This is also optional. It is to pass extra flags like envelope sender address with a command-line option

Return Values

This function returns boolean true or false based on the sent status of the mail. By receiving boolean true that doesn’t mean the mail was sent successfully. Rather, it only represents that the mail sending request is submitted to the server.

PHP sendmail – configurations

We have to configure some directives to make the mail script work in your environment.

Locate your php.ini file and set the mail function attributes. The below image shows the PHP configuration of the mail function.

How to Send Emails with PHP Mail() Function

Set the mail server configuration and the sendmail path with this php.ini section. Then restart the webserver and ensure that the settings are enabled via phpinfo()

Examples to Sendmail in PHP

Sendmail in PHP to send plaintext content

This is a short example of sending plain text content via PHP Script. It sets the mail subject, message and recipient email parameter to sendemail in PHP.

This program print response text based on the boolean returned by the mail() function.

sendmail-with-plain-text.php

<?php
$to = 'recipient@email.com';
$subject = 'Mail sent from sendmail PHP script';
$message = 'Text content from sendmail code.';
// Sendmail in PHP using mail()
if (mail($to, $subject, $message,)) {
    echo 'Mail sent successfully.';
} else {
    echo 'Unable to send mail. Please try again.';
}
?>

PHP Sendmail code to send HTML content

Like the above example, this program also uses the PHP mail() function to send emails. It passes HTML content to the mail function.

For sending HTML content, it sets the content type and other header values with the mail header.

php-mail-with-html-content.php

<?php
$to = 'recipient@email.com';

$subject = 'Mail sent from sendmail PHP script';

$from = 'test@testmail.com';
$headers = "From: $from";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

$message = '<p><strong>Sendmail in PHP with HTML content. </strong></p>';

if (mail($to, $subject, $message, $headers)) {
    echo 'Mail sent successfully.';
} else {
    echo 'Unable to send mail. Please try again.';
}
?>

This program attaches a text file with the email content. It reads a source file using PHP file_get_contents(). It encodes the file content and prepares a mail header to attach a file.

It sets content-type, encoding with the message body to make it work. This script uses the optional $header variable on executing sendmail in PHP.

sendmail-with-attachment.php

<?php
$file = "example.txt";

$to = 'recipient@email.com';
$subject = 'Mail sent from sendmail PHP script';

$content = file_get_contents($file);
$encodedContent = chunk_split(base64_encode($content));

$divider = md5(time());

$headers = "From: TestSupport <example@email.com>\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $divider . "\"\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n";

// prepare mail body with attachment
$message = "--" . $divider. "\r\n";
$message .= "Content-Type: application/octet-stream; name=\"" . $file . "\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment\r\n";
$message .= $encodedContent. "\r\n";
$message .= "--" . $divider . "--";

//sendmail with attachment
if (mail($to, $subject, $message, $headers)) {
    echo 'Mail sent successfully.';
} else {
    echo 'Unable to send mail. Please try again.';
}
?>

Sendmail on form submit

Instead of static values, we can also pass user-entered values to the PHP sendmail. An HTML form can get the values from the user to send mail. We have already seen how to send a contact email via the form.

This example shows a form that collects name, from-email and message from the user. It posts the form data to the PHP on the submit action.

The PHP reads the form data and uses them to prepare mail sending request parameters. It prepares the header with the ‘from’ email. It sets the mail body with the message entered by the user.

All the form fields are mandatory and the validation is done by the browser’s default feature.

sendmail-on-form-submit.php

<?php
if (isset($_POST["submit_btn"])) {

    $to = "recipient@email.com";
    $subject = 'Mail sent from sendmail PHP script';

    $from = $_POST["email"];
    $message = $_POST["msg"];
    $headers = "From: $from";

    // Sendmail in PHP using mail()
    if (mail($to, $subject, $message, $headers)) {
        $responseText = 'Mail sent successfully.';
    } else {
        $responseText = 'Unable to send mail. Please try again.';
    }
}
?>
<html>
<head>
<style>
body {
	font-family: Arial;
	width: 550px;
}
.response-ribbon {
	padding: 10px;
	background: #ccc;
	border: #bcbcbc 1px solid;
	margin-bottom: 15px;
	border-radius: 3px;
}
input, textarea {
	padding: 8px;
	border: 1px solid #ccc;
	border-radius: 5px;
}
#Submit-btn {
	background: #1363cc;
	color: #FFF;
	width: 150px;
}
#email-form {
	border: 1px solid #ccc;
	padding: 20px;
}
.response-ribbon {
}
</style>
</head>
<body>
<?php 
	if(!empty($responseText)) {
	
	?>
<div class="response-ribbon"><?php echo $responseText; ?></div>
<?php 
	}
	?>
<form id="email-form" name="email-form" method="post" action="">
  <table width="100%" border="0" align="center" cellpadding="4"
			cellspacing="1">
    <tr>
      <td><div class="label">Name:</div>
        <div class="field">
          <input name="name" type="text" id="name" required>
        </div></td>
    </tr>
    <tr>
      <td><div class="label">E-mail:</div>
        <div class="field">
          <input name="email" type="text" id="email" required>
        </div></td>
    </tr>
    <tr>
      <td><div class="label">Message:</div>
        <div class="field">
          <textarea name="msg" cols="45" rows="5" id="msg" required></textarea>
        </div></td>
    </tr>
    <tr>
      <td><div class="field">
          <input name="submit_btn" type="submit" id="submit-btn"
							value="Send Mail">
        </div></td>
    </tr>
  </table>
</form>
</body>
</html>

mail sending html form

How to Send Emails with PHP Mail() Function

Leave a Reply

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