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.

<?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

This site uses Akismet to reduce spam. Learn how your comment data is processed.