PHP Email
Email validation is a required action before submitting the user input in the server-side. It checks whether the user has provided a valid email address. Here’s the absolute easiest and effective way to validate an email address using PHP.
The filter_var() function in PHP, provides an easy way for email validation. Use FILTER_VALIDATE_EMAIL filter to validate email address in PHP. The filter_var() function returns the filtered data on success, or FALSE on failure.
$email = "john.doe@example.com";
// Validate email
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "$email is a valid email address";
}else{
echo "$email is not a valid email address";
}
mail($to, $subject, $message, $headers);
Emailing form data:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$to = $_POST['recipient_name'] . "<{$_POST['recipient_email']}>";
$subject = $_POST['subject'];
$body = $_POST['body'];
$headers =
"From: John Doe <johndoe@example.com>\r\n"
. "X-Sender: <johndoe@example.com>\r\n"
. "X-Mailer: PHP\r\n"
. "X-Priority: 1\r\n"
. "Return-Path: <johndoe@example.com>\r\n";
mail($to, $subject, $body, $headers);
}
How to send Cc and Bcc
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$to = $_POST['recipient_name'] . "<{$_POST['recipient_email']}>";
$subject = $_POST['subject'];
$body = $_POST['body'];
$headers =
"From: John Doe <johndoe@example.com>\r\n"
. "X-Sender: <johndoe@example.com>\r\n"
. "Bcc: janedoe@example.com\r\n"
. "Cc: joedoe@example.com\r\n";
mail($to, $subject, $body, $headers);
}
Sending HTML Formatted Emails
You can send HTML emails by sending the additional Content-type and MIME-Version headers:
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
Example: Sending HTML mails in PHP:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$to = $_POST['recipient_name'] . "<{$_POST['recipient_email']}>";
$subject = $_POST['subject'];
$body =
"<html>
<head>
<title>The Suggestion Form</title>
</head>
<body>
<h1>$subject</h1>
<p>".nl2br($_POST['body'])."</p>
</body>
</html>";
$headers =
"From: John Doe <johndoe@example.com>\r\n"
. "MIME-Version: 1.0\r\n"
. "Content-type: text/html; charset=UTF-8\r\n"
. "X-Sender: <johndoe@example.com>\r\n"
. "X-Mailer: PHP\r\n"
. "X-Priority: 1\r\n"
. "Return-Path: <johndoe@example.com>\r\n";
mail($to, $subject, $body, $headers);
}