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:

ParameterDescription
toRequired field. Specifies the receiver / receivers email id.
subjectRequired field. Specifies the subject of the email.
messageRequired. Specifies the message to be sent.
headersOptional. Specifies additional headers, like From, Cc, and Bcc.
parametersOptional. Specifies an additional parameter to the send in email

Example 1: Send an email.

<?php
$to = “mailto@example.com”;
$subject = “php email example”;
$msg = “Your message here.”;
mail($to,$subject,$msg);
?>

Example 2: Sending HTML in email.

<?php
$to = “mailto@example.com”;
$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>
</table></body></html>”;

// 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: myboss@example.com’ . “\r\n”;

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

Leave a Reply