How to Send Email in PHP: Simple Guide with Examples
To send an email in PHP, use the
mail() function with parameters for recipient, subject, message, and optional headers. This function sends the email through the server's mail system with a simple call like mail('to@example.com', 'Subject', 'Message').Syntax
The mail() function in PHP sends an email with the following parameters:
- to: The recipient's email address.
- subject: The email subject line.
- message: The body of the email.
- headers (optional): Additional headers like From, Cc, Bcc.
- parameters (optional): Additional command line parameters for the mail program.
php
bool mail(string $to, string $subject, string $message, string $headers = null, string $parameters = null)
Example
This example shows how to send a simple email with a subject and message. It also sets the From header to specify the sender's email address.
php
<?php $to = 'friend@example.com'; $subject = 'Hello from PHP'; $message = "Hi there,\nThis is a test email sent using PHP."; $headers = 'From: sender@example.com' . "\r\n" . 'Reply-To: sender@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); if (mail($to, $subject, $message, $headers)) { echo 'Email sent successfully.'; } else { echo 'Email sending failed.'; } ?>
Output
Email sent successfully.
Common Pitfalls
Common mistakes when sending email in PHP include:
- Not setting the
Fromheader, which can cause the email to be rejected or marked as spam. - Incorrect line breaks in headers; always use
\r\nfor new lines. - Assuming
mail()works on all servers; some servers require proper mail server setup. - Not validating email addresses before sending.
Here is a wrong and right way to set headers:
php
<?php // Wrong: Missing From header mail('friend@example.com', 'Subject', 'Message'); // Right: With From header $headers = 'From: sender@example.com' . "\r\n"; mail('friend@example.com', 'Subject', 'Message', $headers); ?>
Quick Reference
Tips for sending email in PHP:
- Always include a
Fromheader to avoid spam filters. - Use
\r\nfor line breaks in headers. - Test email sending on your server environment.
- Consider using libraries like PHPMailer for advanced features.
Key Takeaways
Use PHP's mail() function with recipient, subject, message, and headers to send email.
Always set the From header to specify the sender and avoid spam issues.
Use \r\n for line breaks in email headers to ensure proper formatting.
Test email sending on your server as mail() depends on server configuration.
For complex needs, use dedicated libraries like PHPMailer instead of mail().