PHP - Sending Emails

The PHP mail() function allows us to send emails directly from a script. The behavior of this function is affected by settings in php.ini. Hence, the php.ini file must be configured correctly with the details of how the system should send emails.

PHP mail() function

The PHP mail() function is used to send mail directly from a script.

Syntax

mail(to, subject, message, additional_headers, additional_params)

Parameters

  • to - Required. Specify receiver or receivers of the mail.

  • subject - Required. Specify the subject of the email to be sent. This parameter cannot contain any newline character.

  • message - Required. Specify the message to be sent. Each line should be separated with a CRLF (\r\n). Lines should not be larger than 70 characters. Windows only: If a full stop is found on the start of a line, it is removed. To counter-act this, replace these occurrences with a double dot.

  • additional_headers - Optional. Specify string or array to be inserted at the end of the email header. This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n). If an array is passed, its keys are the header names and its values are the respective header values. When sending mail, the mail must contain a From header. This can be set with the additional_headers parameter, or a default can be set in php.ini.

  • additional_params - Optional. Specify additional flags to pass as command line options to the program configured to be used when sending mail, as defined by the sendmail_path configuration setting. For example, this can be used to set the envelope sender address when using sendmail with the -f sendmail option.

Return Value

Returns true if the mail was successfully accepted for delivery, false otherwise. Please note that even if the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

Example: sending mail

In the example below, the mail() function is used to send a simple mail.

<?php
//the message
$message = "Line 1\r\nLine 2\r\nLine 3";

//in case of lines larger than 70 characters
//wordwrap() function can be used
$message = wordwrap($message, 70, "\r\n");

//the subject
$subject = "My Subject";

//sending mail
$retval = mail('user@example.com', $subject, $message);

if($retval == true) {
  echo "Message sent successfully!";
} else {
  echo "Message could not be sent!";
}
?>