Welcome to this comprehensive tutorial on PHP Mail Parameters! By the end of this lesson, you'll be able to send emails using PHP, making it perfect for beginners and intermediate learners. Let's dive in!
PHP Mail is a built-in function in PHP that allows you to send emails directly from your PHP scripts. It's incredibly useful for creating contact forms, password reset notifications, and more!
To set up a PHP email, we'll need to know some parameters:
From (Sender's Email): The email address that will appear as the sender of the email.
To (Receiver's Email): The recipient's email address.
Subject: The subject line of the email.
Body: The content of the email.
Headers (Optional): Additional information that can be included in the email's header, such as the email's priority or the reply-to address.
Let's start with a simple example:
<?php
$to = "receiver@example.com";
$subject = "Hello from PHP!";
$message = "This is a test email sent from PHP.";
$headers = "From: sender@example.com";
mail($to, $subject, $message, $headers);
?>π‘ Pro Tip: Make sure you replace sender@example.com and receiver@example.com with your actual email addresses.
If you need to send emails with attachments, you can use the mail() function in a similar way:
<?php
$to = "receiver@example.com";
$subject = "Attached File";
$message = "This is an email with an attachment.";
$headers = "From: sender@example.com";
// Attachment name and type
$file_name = "example.txt";
$file_type = "text/plain";
// Read the contents of the file
$file = file_get_contents($file_name);
// Base64 encode the file contents
$encoded_file = base64_encode($file);
// Attachment headers
$headers .= "\r\nContent-Type: {$file_type}; name=\"{$file_name}\"";
$headers .= "\r\nContent-Disposition: attachment";
$headers .= "\r\nContent-Transfer-Encoding: base64";
// Combine the message and attachment
$message = chunk_split(base64_encode($file)).$message;
// Send the email
mail($to, $subject, $message, $headers);
?>What is the purpose of the `mail()` function in PHP?
Keep learning, and happy coding! ππ