How to send Email using PHP

Posted on: November 22, 2017 at 3:19 am by Sanket Mhaddalkar - No Comments

How to send Email using PHP

 

In this article, we will see how we can send a mail using PHP. Mail functionality is mainly used in Contact Forms on a website. So that users visiting a particular site can contact admins or management person of that website.

 

For sending a mail through PHP we use the mail() function. mail() method was introduced with PHP version 4. Four parameters are required to send mail successfully.

 

Parameters required are:

 

1. to – Required. As it is the person to whom the mail will be sent.

 

2. subject – Required. Here we will specify the subject of the mail.

 

3. message – Required. Here we will write the message that is to be sent. Each line is to be separated with (\n), so as to add a new line in message. Also, each line in the message should not exceed 70 characters.

 

4. headers – Required. Here we will add headers like From, Cc and Bcc to the mail. The headers should be separated with (\r\n). For sending a mail From headers is required, whereas Cc and Bcc are optional to use.

 

5. parameters – Optional. Specifies an additional parameter to the send mail program.

 

Syntax for mail() function:

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

 

*Note: if you are working on localhost or server, you need to setup the SMTP server first.

 

Examples for sending a mail:

 

Sending plain text mail:

<?php

$to = "user@example.com"; 
$subject = "How to send mail with PHP"; 
$message = "This is an message to show the example."; 

$headers = "From: webmaster@example.com \r\n"; 
$headers .= "Cc: webmaster@example.com \r\n"; 
$headers .= "MIME-Version: 1.0\r\n"; 
$headers .= "Content-type: text/plain"; 

$mailStatus = mail($to, $subject, $message, $headers); 

if($mailStatus) { 
echo "Mail sent successfully."; 
} 
else { 
echo "Mail sent failed."; 
}

?>

 

Sending mail in HTML:

<?php

$to = "user@example.com"; 
$subject = "How to send mail with PHP"; 

$message = "<h1>Welcome to Sanktips.com</h1>"; 
$message .= "<p>This is an HTML message to show the example.</p>"; 
$message .= "<p>Follow us on Facebook, Twitter and Google+</p>"; 

$headers = "From: webmaster@example.com \r\n"; 
$headers .= "Cc: webmaster@example.com \r\n"; 
$headers .= "MIME-Version: 1.0\r\n"; 
$headers .= "Content-type: text/html"; 

$mailStatus = mail($to, $subject, $message, $headers); 

if($mailStatus){ 
echo "Mail sent successfully.";
} 
else { 
echo "Mail sent failed."; 
}

?>

 

Hope you find this article helpful. Join us on Facebook, Twitter and Google+ to get more updates on Android and Web Development Tutorials.

 



About Author:

I am Certified Java Developer. I Develop Android Applications and Websites. I also love blogging so as to share my experiences with others.



Subscribe to our Newsletter

Join our mailing list to receive
the latest news and updates from our team.