Sending Email in PHP Using mail() Function

PHP

If you have to send email in PHP, then simply use the in-built mail() function. It must be enabled by your PHP web host. It normally is. If you need to see whether PHP mail is activated or not, just try the simplest example from below. If the mail is delivered, then the host supports PHP mail.

Here’s a simple format for using mail

mail(to, subject, message, additional headers, additional parameters)

to
The receiver’s email address. Format: [email protected] or [email protected], [email protected] or Ashish <[email protected]>

subject
The email’s subject.

message
The email’s message. A single line should not be longer then 70 characters. For new lines use “rn” (including the double quotes). If your message lines are longer than 70 characters use the wordwrap function wordwrap($message, 70, “rn”);. Message can be in HTML as well.

additional headers
Additional information like the from, CC, BCC, reply-to email.

additional parameters
Any other additional parameters. This is quite advanced and is not always required.

Example:

<?php
mail('[email protected]','Subject','Message');
?>
Output:
Sends an email to [email protected] with Subject and Message.

Here’s a bit more advanced example:

<?php
$to = '[email protected]';
$subject = 'Namaste';
$headers = 'From: [email protected]';
$message = "Hello How Are yournI am doing great herernI hope all is wellrnBye Bye"; //Notice that rn doesn't have space to separate them.
$message = wordwrap($message, 70, "rn");
mail($to,$subject,$message,$headers);
?>

Headers can contain a whole lot of other information. Here’s how you use headers to the fullest.

<?php
$to = '[email protected]';
$subject = 'Namaste';
$headers = 'From: [email protected]';
$message = "Hello How Are yournI am doing great herernI hope all is wellrnBye Bye";
$message = wordwrap($message, 70, "rn");

$headers   = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: Sending Person <[email protected]>";
$headers[] = "Bcc: BCC Person <[email protected]>";
$headers[] = "Reply-To: Reply Receiver <[email protected]>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();

mail($to, $subject, $message, implode("rn", $headers));
?>