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.
<?php
mail('recipient@domain.com', 'Mail Subject', 'Mail test content');
?>
In 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.
The PHP mail() is to sendmail from an application. Let’s see the PHP configurations required to make the mail() function work. Also, we will see the common syntax and parameters of this PHP function below.
mail(
string $recipient_email,
string $subject,
string $message,
array|string $headers = [],
string $additional_params = ""
)
$recipient_email
One or more comma-separated value that is the target mail addresses. The sample format of the values are,
$subject
Mail subject. It should satisfy RFC 2047.
$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.
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.
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.
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().
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.';
}
?>
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.';
}
?>
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>
PHP mail() function has some limitation. To have a full-fledge functionality to sendmail in PHP, I prefer to use the PHPmailer library.
This library is one of the best that provides advanced mailing utilities. We have seen examples already to sendmail in PHP using PHPMailer via SMTP. If you are searching for the code to sendmail using OAuth token, the linked article has an example.
This example uses a minimal script to sendmail in PHP with PHPMailer via SMTP. It loads the PHPMailer library to create and set the mail object.
The mail object is used to configure the mail parameters. Then it invokes the send() method of the PHPMailer class to send mail.
Download PHPMailer from Github and put it into the vendor of this example directory. Replace the SMTP configurations in the below script to make this mail script working.
sendmail-in-php-via-smtp.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/Exception.php';
require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/vendor/phpmailer/phpmailer/src/SMTP.php';
$mail = new PHPMailer(true);
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = "";
$mail->Password = "";
$mail->SMTPSecure = "ssl";
$mail->Port = 465;
$mail->From = "test@testmail.com";
$mail->FromName = "Full Name";
$mail->addAddress("recipient@email.com", "recipient name");
$mail->isHTML(true);
$mail->Subject = "Mail sent from php send mail script.";
$mail->Body = "<i>Text content from send mail.</i>";
$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
?>
The PHP provides alternate mail functions to sendmail. Those are listed below.
The mail sending examples above provides code to sendemail in PHP. It supports sending various types of content, file attachments in the mail.
The elaboration on PHP in-built mail() function highlights the power of this function.
Hope this article will be helpful to learn more about how to sendmail in PHP.
Download
thank you so mutch very helpfull
Welcome Sehbani.
Valuable content
Thank you Raj.
i wants to become a professional php programmer. please suggest some good books to read.
Head first PHP and MySQl is a nice one to start with.