Introduction
PHP allows developers to send emails directly from a website using built-in functions and email libraries. Email handling is useful for contact forms, registration confirmations, password reset messages, and notifications. In this chapter, you will practise sending emails, setting recipients, adding subjects, and handling email-related tasks.
Question 1: Send a Simple Email Using mail()
Problem Statement
Create a PHP program that sends a simple email to a recipient using the mail() function.
PHP Solution
<?php
$to = "student@example.com";
$subject = "Welcome to PHP";
$message = "Welcome! You are learning email handling in PHP.";
$headers = "From: admin@example.com";
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully.";
} else {
echo "Email could not be sent.";
}
?>
Sample Output
Email sent successfully.
Explanation
$tostores the recipient’s email address.$subjectcontains the email subject.$messagecontains the email body.$headersspecifies the sender’s email address.mail()attempts to send the email.- The
ifstatement checks whether PHP successfully handed the message to the configured mail system.
Note: A successful result from mail() does not guarantee that the recipient received the email.
Concepts Covered
mail()- Email recipient
- Email subject and message
- Email headers
Question 2: Send an Email with a Different Subject
Problem Statement
Create a PHP program that sends an email with a subject related to student registration.
PHP Solution
<?php
$to = "student@example.com";
$subject = "Student Registration Confirmation";
$message = "Your registration request has been received.";
$headers = "From: admission@example.com";
if (mail($to, $subject, $message, $headers)) {
echo "Registration email submitted successfully.";
} else {
echo "Unable to submit registration email.";
}
?>
Sample Output
Registration email submitted successfully.
Explanation
The $subject variable contains the title of the email. The recipient sees this subject in their inbox. The message explains that the registration request has been received.
Concepts Covered
- Email subject
- Email message
- Sending registration notifications
Question 3: Send an Email with CC
Problem Statement
Send an email to a student and include a copy for the training department using the CC header.
PHP Solution
<?php
$to = "student@example.com";
$subject = "Course Information";
$message = "Your course details are ready.";
$headers = "From: admin@example.com\r\n";
$headers .= "Cc: training@example.com\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "Email with CC submitted successfully.";
} else {
echo "Email could not be submitted.";
}
?>
Sample Output
Email with CC submitted successfully.
Explanation
Ccmeans Carbon Copy.- The main recipient receives the email.
- The CC recipient also receives a copy.
\r\nseparates individual email headers..=adds another header to the existing string.
Concepts Covered
- CC header
- Multiple email headers
- Header line separation
Question 4: Send an Email with BCC
Problem Statement
Send a course announcement to a student while secretly sending a copy to the administration department using BCC.
PHP Solution
<?php
$to = "student@example.com";
$subject = "New Course Announcement";
$message = "A new PHP course is available.";
$headers = "From: admin@example.com\r\n";
$headers .= "Bcc: administration@example.com\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "Email with BCC submitted successfully.";
} else {
echo "Email could not be submitted.";
}
?>
Sample Output
Email with BCC submitted successfully.
Explanation
BCC means Blind Carbon Copy.
The BCC recipient receives a copy of the email, but the main recipient cannot see the BCC address in the email’s recipient list.
BCC is useful when sending announcements to multiple recipients without exposing their email addresses.
Concepts Covered
- BCC header
- Private email copies
- Email privacy
Question 5: Validate an Email Address Before Sending
Problem Statement
Create a PHP program that checks whether an email address is valid before attempting to send an email.
PHP Solution
<?php
$email = "student@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Email address is valid.";
} else {
echo "Invalid email address.";
}
?>
Sample Output
Email address is valid.
Explanation
$emailstores the email address.filter_var()checks whether the address follows a valid email format.FILTER_VALIDATE_EMAILis the validation rule.- If the address passes validation, PHP displays the success message.
Remember: Email format validation does not confirm that the mailbox exists or can receive messages.
Concepts Covered
- Email validation
filter_var()FILTER_VALIDATE_EMAIL
Question 6: Send an Email with a Reply-To Address
Problem Statement
Send a course-related email from the administration department while allowing the recipient to reply to the support department.
PHP Solution
<?php
$to = "student@example.com";
$subject = "Course Support Information";
$message = "Contact our support team if you need assistance.";
$headers = "From: admin@example.com\r\n";
$headers .= "Reply-To: support@example.com\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "Email with Reply-To submitted successfully.";
} else {
echo "Email could not be submitted.";
}
?>
Sample Output
Email with Reply-To submitted successfully.
Explanation
Fromidentifies the sender.Reply-Tospecifies the address that should receive replies.- When the recipient clicks Reply, their email application normally uses the Reply-To address.
Concepts Covered
- From header
- Reply-To header
- Email replies
Question 7: Send an HTML Email
Problem Statement
Create an email containing HTML formatting, including a heading and a paragraph.
PHP Solution
<?php
$to = "student@example.com";
$subject = "Welcome to Our Training Institute";
$message = "
<html>
<body>
<h2>Welcome Student!</h2>
<p>Your course registration is successful.</p>
<p>Thank you for joining us.</p>
</body>
</html>
";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
$headers .= "From: admin@example.com\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "HTML email submitted successfully.";
} else {
echo "HTML email could not be submitted.";
}
?>
Sample Output
HTML email submitted successfully.
Explanation
An HTML email can contain headings, paragraphs, links, and other formatting.
MIME-Versionspecifies the MIME version.Content-Type: text/htmltells the email application that the message contains HTML.charset=UTF-8supports a wide range of characters and languages.
Concepts Covered
- HTML email
- MIME headers
- Content-Type
- UTF-8 encoding
Question 8: Send an Email to Multiple Recipients
Problem Statement
Send the same course announcement to three students using a single email message.
PHP Solution
<?php
$to = "student1@example.com, student2@example.com, student3@example.com";
$subject = "PHP Course Announcement";
$message = "Your PHP practice session is scheduled for Monday.";
$headers = "From: admin@example.com";
if (mail($to, $subject, $message, $headers)) {
echo "Email submitted to all recipients.";
} else {
echo "Email could not be submitted.";
}
?>
Sample Output
Email submitted to all recipients.
Explanation
The $to variable contains multiple email addresses separated by commas.
PHP passes the message to the configured mail system for delivery to those recipients.
For privacy, avoid exposing a large recipient list in the To field. Use BCC or a suitable mailing service when sending bulk messages.
Concepts Covered
- Multiple recipients
- Recipient separation
- Email privacy
Question 9: Send an Email After Checking the Recipient Address
Problem Statement
Create a PHP program that validates a recipient email address and sends a course notification only when the address passes validation.
PHP Solution
<?php
$to = "student@example.com";
$subject = "Course Notification";
$message = "Your next PHP class is scheduled for tomorrow.";
$headers = "From: admin@example.com";
if (filter_var($to, FILTER_VALIDATE_EMAIL)) {
if (mail($to, $subject, $message, $headers)) {
echo "Email submitted successfully.";
} else {
echo "Email submission failed.";
}
} else {
echo "Please enter a valid email address.";
}
?>
Sample Output
Email submitted successfully.
Explanation
This program performs two checks:
- First, PHP checks whether the recipient address has a valid email format.
- If the address passes validation,
mail()attempts to submit the message. - If the address is invalid, the program does not attempt to send the email.
This prevents unnecessary email attempts using incorrectly formatted addresses.
Concepts Covered
- Email validation
- Nested conditions
mail()- Email submission status
Question 10: Create a Complete Student Email Notification System
Problem Statement
Create a PHP program that accepts student details through variables, validates the student’s email address, and sends a course registration confirmation.
PHP Solution
<?php
$studentName = "Rahul";
$studentEmail = "rahul@example.com";
$courseName = "PHP Programming";
if (
trim($studentName) !== "" &&
filter_var($studentEmail, FILTER_VALIDATE_EMAIL)
) {
$to = $studentEmail;
$subject = "Course Registration Confirmation";
$message = "
Hello $studentName,
Your registration for $courseName has been received.
Thank you for registering.
";
$headers = "From: admission@example.com\r\n";
$headers .= "Reply-To: support@example.com\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "Registration email submitted successfully.";
} else {
echo "Email submission failed.";
}
} else {
echo "Please provide valid student details.";
}
?>
Sample Output
Registration email submitted successfully.
Explanation
This example combines the main concepts covered in this chapter.
- Student name, email, and course are stored in variables.
trim()checks that the student name is not empty or only whitespace.filter_var()validates the email format.- The email subject and message are created.
- The From and Reply-To headers are added.
mail()attempts to submit the registration confirmation.
Concepts Covered
- Student email notifications
- Email validation
- Email headers
mail()- Conditional processing
Key Takeaways
- PHP uses the
mail()function to submit emails through a configured mail system. - The
mail()function accepts recipient, subject, message, and optional headers. - CC sends a visible copy, while BCC sends a hidden copy.
- Reply-To specifies the address used when a recipient replies.
- HTML emails require appropriate MIME and Content-Type headers.
filter_var()withFILTER_VALIDATE_EMAILchecks email format.- Email delivery depends on the server’s mail configuration.
Frequently Asked Questions (FAQs)
1. What is email handling in PHP?
Email handling in PHP means sending messages from a website to users, students, customers, or administrators using PHP email functionality.
2. Which function is used to send emails in PHP?
PHP provides the mail() function to submit emails through the configured mail system.
3. What are the main arguments of the mail() function?
The main arguments are recipient, subject, message, and optional additional headers.
4. Can PHP send HTML emails?
Yes. PHP can send HTML emails by specifying the appropriate MIME version and Content-Type: text/html headers.
5. What is the difference between CC and BCC?
CC sends a visible copy of an email, while BCC sends a copy without showing that recipient’s address to other recipients.
6. How can we validate an email address in PHP?
Use filter_var() with FILTER_VALIDATE_EMAIL to check the email address format.
7. Why does mail() return true but the email is not received?
It generally means the message was accepted for processing by the configured mail system. It does not confirm final delivery. The message may be rejected, delayed, or marked as spam.
8. Can we send emails using PHP on localhost?
Yes, but a local server such as XAMPP needs a working mail transport configuration or an external SMTP service.
9. What is the purpose of the Reply-To header?
The Reply-To header specifies the email address that should receive replies from the recipient.
10. Is PHPMailer useful for PHP email handling?
Yes. PHPMailer is a popular PHP library that supports authenticated SMTP, HTML messages, attachments, and other email features.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
