Nowadays, Sending messages through email are very common for a web application,thousands of Emails send and received every day.for example sending newsletters to your subscribers, sending email for verification when a user create an account.
Syntax:
mail(to, subject, message, headers, parameters)
| Parameter | Description |
|---|---|
| to | The recipient's e-mail address |
| subject | Subject of mail |
| message | Content/message of the mail. |
| headers | additional headers you want to include such as "cc","from"(optional) |
| parameters | additional parameters to send(optional) |
To use mail() function, you need to set SMTP mailserver and port:
Warning: mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
for example:
[mail function] ; For Win32 only. ; http://php.net/smtp SMTP = smtp.gmail.com ; http://php.net/smtp-port smtp_port = 465 sendmail_from = yourusername@gmail.com
<?php
$to = "admin@lautturi.org";
$subject = "hello lau,good news";
$message = "You passed the test. Congratulations! ";
$from = "yourusername@gmail.com";
$headers = "From:".$from;
if(mail($to,$subject,$message,$headers)){
echo "Mail sent successfully.";
}
else{
echo "Unable to send the mail.";
}
?>
To send an HTML email, we need to set Content-type in the header parameter.
<?php
$to = "admin@lautturi.org";
$subject = "hello lau,good news";
$message <<< EOT
<html><body>
<h2>Congratulations!</h2>
<p>You passed the test.</p>
</body></html>
EOT;
$from = "yourusername@gmail.com";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From:".$from;
if(mail($to,$subject,$message,$headers)){
echo "Mail sent successfully.";
}
else{
echo "Unable to send the mail.";
}
?>