Welcome back to CodeYourCraft! Today, we're diving into the world of PHP Mail with additional parameters. If you're new to PHP, don't worry! We'll start from the ground up and gradually introduce you to the more advanced concepts.
PHP Mail is a built-in function in PHP that allows you to send emails from your server. It's a powerful tool for communication in web development, be it for notifications, password recovery, or transactional emails.
Let's start with a simple example:
<?php
$to = "recipient@example.com";
$subject = "Hello World";
$message = "This is a test email sent using PHP.";
$headers = "From: sender@example.com" . "\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully!";
} else {
echo "Failed to send email.";
}
?>In this example, we're sending an email to recipient@example.com with the subject "Hello World" and the message "This is a test email sent using PHP." The email is sent from sender@example.com.
Now, let's explore some additional parameters you can use with the mail() function to customize your emails even further.
The content type determines the MIME type of the email body. By default, it's set to text/plain, but you can change it to text/html for HTML emails:
$headers = "Content-type: text/html; charset=UTF-8" . "\r\n";You can set a reply-to address to ensure that responses from the recipient are sent to the correct email address:
$headers .= "Reply-To: reply@example.com" . "\r\n";You can also add CC (carbon copy) and BCC (blind carbon copy) recipients to an email:
$cc = "cc@example.com";
$bcc = "bcc@example.com";
$headers .= "Cc: $cc" . "\r\n";
$headers .= "Bcc: $bcc" . "\r\n";What does the `mail()` function do in PHP?
Now it's time for you to put your newfound knowledge into practice! Create a simple PHP script that sends an email with an HTML body, a reply-to address, and CC and BCC recipients.
Remember, practice makes perfect! Don't be afraid to experiment and ask questions. Happy coding! π