PHP has a built-in mail() function, but for reliable email delivery you should use an SMTP library like PHPMailer.
Built-in mail()
Works for simple cases but requires proper server configuration and has deliverability issues.
PHPMailer (Recommended)
Install via Composer: composer require phpmailer/phpmailer. Supports SMTP, TLS, HTML emails, and attachments.
Email Best Practices
- Use a transactional email service (Mailgun, SendGrid, Amazon SES)
- Always set
From address to a domain you control - Set up SPF, DKIM, and DMARC DNS records
Example
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
// SMTP Config
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@gmail.com';
$mail->Password = 'your-app-password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// Recipients
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('recipient@example.com', 'Joe User');
// Content
$mail->isHTML(true);
$mail->Subject = 'Hello from PHPMailer!';
$mail->Body = '<b>This is a test email.</b>';
$mail->AltBody = 'This is a test email.';
$mail->send();
echo 'Email sent!';
} catch (Exception $e) {
echo 'Error: ' . $mail->ErrorInfo;
}