PHP Mail Function Tutorial

Introduction

PHP includes a native mail() function that is essential to any website. Just as the name suggests, the function is used to send an email to a designated email address.

The Function

mail(to, subject, message, headers);

The mail() function returns either true if the email was sent successfully, or false if there was an error. Keep in mind, although the function may return true, that doesn’t garuntee the email was received.

Parameters

The mail() function contains 4 essential parameters.

1. the to parameter specifies the receivers email address. (required)

2. the subject parameter specifies the subject of the email. (required)

3. the message parameter specifies the actual body of the email. The body lines should be separated by a line break (\n) within the actual body text. (required)

4. the headers parameter is an optional setting that can be used to specify additional headers such as From, Cc, and Bcc. This paramater should be used to set the From setting, however as said this is optional and if it is left empty the From setting will come from php.ini (optional)

Examples

Example #1 – Basic mail() Function use

// Body Text
$body = “This is the body text\nThis is the second line of the body text!”;

// Send Mail
mail(“email@website.com”, “Email Subject”, $body);

?>

Example #2 – Use of Headers

// Body Text
$body = “This is the body text\nThis is the second line of the body text!”;

// Headers

$headers = “From: email@website.com\r\nCC: email2@website.com”;

// Send Mail
mail(“email@website.com”, “Email Subject”, $body, $headers);

?>

Conclusion

This concludes this brief introduction to the PHP mail function. Look forward to more php tutorials from me =)

Questions?

If you have any questions, leave a comment and I will get back to you!

$txt = “First line of text\nSecond line of text”;

// Use wordwrap() if lines are longer than 70 characters
$txt = wordwrap($txt,70);

// Send email
mail(“somebody@example.com”,”My subject”,$txt);
?>

About Author

Leave A Reply