Learn to send email using PHP Mail Function
The mail()
function in PHP is used to send emails directly from the script
. A working email system is required for the proper functioning of mail function. mail()
in PHP is:
- very efficient and a cost effective way of communication.
- developers also use this function to receive errors while coding.
- also used for newsletter subscribers.
- also very helpful while providing resetting password links to users.
mail
function uses SMTP (Simple Mail Transfer Protocol) to send mails. The configuration settings for this function are done in a php.ini
file located inside the installation folder. Default settings are as follows:
[mail function]
SMTP=localhost // DNS or the IP address of the SMTP server.
smtp_port=25 // SMTP port number
mail()
Syntax
// syntax
mail(to, subject, message, headers, parameters);
to |
Receiver of the email. Required. |
subject |
Subject of the email. Required. |
message |
Message to be sent. The message must not exceed 70 characters. Required. |
headers |
Header consists of information like from, cc, bcc. Optional. |
parameters |
Additional parameters to the sendmail program. Optional. |
It returns true
on successful sending of mail, otherwise it returns false
.
// Code Example
<?php
$to = "[email protected]";
$subject = "Demo mail";
$body = "Mail function is working successfully";
$headers = "From: [email protected]" . "\r\n" .
"CC: [email protected]";
$res = mail($to, $subject, $body, $headers);
if($res == TRUE){
echo “Mail sent”;
}
?>
Code example to send HTML content using mail()
<?php
$to = "[email protected]";
$subject = "Demo HTML mail";
$body = "<html>
<head>
<title>HTML Email Example</title>
</head>
<body>
<h5>Sending HTML mail</h5>
</body>
</html>";
// Setting content-type
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers = "From: [email protected]" ."\r\n".
"CC: [email protected]";
$res = mail($to, $subject, $body, $headers);
if($res == TRUE){
echo “Mail sent”;
}else{
echo “Sending failed”;
}
?>
There could be a case, we need to send a form in email. Sanitizing and filtering of variables is necessary for the security of data. Functions in relation to this are as under:
// syntax
filter_var($field, SANITIZATION_TYPE);
Understanding of Syntax
filter_var
: function for sanitization and filter.
$field
: value to be filtered.
SANITIZATION_TYPE
: type of sanitization and filtration to be performed such as:
|
returns true if email id is valid. |
|
removes illegal characters from an email address. |
|
removes illegal characters from URLs. |
|
removes tags from string values. |