Day 23: Sending Emails in PHP

mail() function is use to send an email in PHP.

Syntax: mail( to, subject, message, headers, parameters );

mail function requires 3 mandatory arguments and 2 optional arguments:

Parameter Description
to Required field. Specifies the receiver / receivers email id.
subject Required field. Specifies the subject of the email.
message Required. Specifies the message to be sent.
headers Optional. Specifies additional headers, like From, Cc, and Bcc.
parameters Optional. Specifies an additional parameter to the send in email

Example 1: Send an email.

$to = “”;
$subject = “php email example”;
$msg = “Your message here.”;

Example 2: Sending HTML in email.

$to = “”;
$subject = “Sending HTML in email”;
$msg = “<html><head><title>HTML email</title></head><body><p>Sending email with html constants.</p>
<table><tr><td>User Name : </td> <td>Albert</td></tr> <tr><td>Password : </td> <td>12345</td></tr>

// headers parameter is required when sending HTML email as below:
$headers = “MIME-Version: 1.0” . “\r\n”;
$headers .= “Content-type:text/html;charset=UTF-8” . “\r\n”;

// More values that we can pass in headers
$headers .= ‘From: ‘ . “\r\n”;
$headers .= ‘Cc:’ . “\r\n”;

if(mail($to,$subject,$message,$headers)) {
echo “Mail sent successfully”;
} else {
echo “Error while sending mail.”;

Leave a Reply