How to send email using php mail function
The classic PHP mail()
function!
To send an email using the PHP mail()
function, you'll need to provide the following information:
- To: The recipient's email address.
- Subject: The subject line of the email.
- Body: The email body content.
- From: The sender's email address.
- Headers: Optional headers, such as
From
,Reply-To
, andCC
.
Here's a basic example of how to use the mail()
function:
<?php
// Define the email variables
$to = '[email protected]';
$subject = 'Test Email';
$body = 'This is a test email sent using PHP mail() function.';
$from = '[email protected]';
// Define the headers
$headers = 'From: '. $from. "\r\n".
'Reply-To: '. $from. "\r\n".
'CC: '. '[email protected]'. "\r\n";
// Send the email
if (mail($to, $subject, $body, $headers)) {
echo 'Email sent successfully!';
} else {
echo 'Error sending email.';
}
?>
In this example:
- We define the email variables:
to
,subject
,body
, andfrom
. - We define the headers using the
From
,Reply-To
, andCC
headers. - We use the
mail()
function to send the email, passing in theto
,subject
,body
, andheaders
variables. - We check if the email was sent successfully using the
mail()
function's return value (which istrue
if the email was sent, andfalse
otherwise).
Note that the mail()
function is a simple, low-level function that doesn't provide any error handling or logging. If you need more advanced features, such as email validation, spam filtering, or logging, you may want to consider using a more robust email library or service.
Also, keep in mind that the mail()
function is not secure, as it sends emails in plain text. If you need to send sensitive information, consider using a more secure method, such as using a library like PHPMailer or SwiftMailer.