Prompt
How do I send emails from a PHP application?
Latest observation
Sep 23, 2026
OpenAI APIWeb search: off
The common ways to send email from a PHP app are:
1) Use a mail library over SMTP
This is the most reliable approach. The most popular library is PHPMailer.
Install with Composer
composer require phpmailer/phpmailer
Example with SMTP
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_username';
$mail->Password = 'your_password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // or PHPMailer::ENCRYPTION_SMTPS
$mail->Port = 587;
$mail->setFrom('from@example.com', 'My App');
$mail->addAddress('to@example.com', 'Recipient Name');
$mail->isHTML(true);
$mail->Subject = 'Hello from PHP';
$mail->Body = '<p>This is a test email.</p>';
$mail->AltBody = 'This is a test email.';
$mail->send();
echo 'Message sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
2) Use PHP’s built-in mail() function
This is simpler, but less reliable and often not recommended for production.
$to = 'user@example.com';
$subject = 'Test email';
$message = 'Hello from PHP';
$headers = 'From: webmaster@example.com' . "\r\n" .
'Reply-To: webmaster@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
Downsides of mail()
- Depends on server mail configuration
- Often ends up in spam
- Harder to debug
- No built-in authentication/TLS handling
3) Use a transactional email service
For apps, this is often best:
- SendGrid
- Mailgun
- Amazon SES
- Postmark
These services usually provide:
- Better deliverability
- SMTP or HTTP APIs
- Bounce/complaint tracking
- Templates and logs
Best practice
For most applications:
- Use PHPMailer or Symfony Mailer
- Send via SMTP
- Use a real email provider
- Set up SPF, DKIM, and DMARC for your domain
If you want, I can show you:
- a PHPMailer example with Gmail/SMTP,
- how to send HTML emails with attachments, or
- how to use Symfony Mailer instead.