PHP can send email three ways: the built-in mail() function, an SMTP library such as PHPMailer, or an HTTPS request to an email API. mail() is the one most tutorials start with and the one most likely to end up in spam. For anything users rely on, use PHPMailer over authenticated SMTP or an email API.
Why mail() is not enough
mail() does not talk to a mail provider. It passes the message to the server’s local sendmail program, which then tries to deliver it from the web server’s IP address. There is no login, no DKIM signature for your domain, and usually no SPF record that covers the web server. Receiving servers notice, and the mail is filtered or rejected. Many hosts also disable or throttle mail().
Option 1: an email API with cURL
PHP’s cURL extension is enabled on almost every host, so this needs no Composer packages. The example uses Mailcandor’s REST API.
<?php
function send_email(array $email, ?string $idempotencyKey = null): string
{
$headers = [
'Authorization: Bearer ' . getenv('MAILCANDOR_KEY'),
'Content-Type: application/json',
];
if ($idempotencyKey !== null) {
$headers[] = 'Idempotency-Key: ' . $idempotencyKey;
}
$ch = curl_init('https://api.mailcandor.com/v1/emails');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => json_encode($email, JSON_THROW_ON_ERROR),
CURLOPT_TIMEOUT => 10,
]);
$body = curl_exec($ch);
if ($body === false) {
throw new RuntimeException('Network error: ' . curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$data = json_decode($body, true);
if ($status !== 202) {
throw new RuntimeException($data['error']['type'] . ': ' . $data['error']['message']);
}
return $data['id'];
}
$id = send_email([
'from' => 'Acme <hello@acme.com>',
'to' => 'sam@example.com',
'subject' => 'Your receipt',
'html' => '<p>Thanks for your order.</p>',
'text' => 'Thanks for your order.',
]);
The API answers 202 with an id as soon as the email is queued. Delivery results come later as webhooks.
Multiple attachments
Add one entry per file, with the content base64-encoded:
$files = ['invoice-1042.pdf' => 'application/pdf', 'terms.pdf' => 'application/pdf'];
$attachments = [];
foreach ($files as $name => $type) {
$attachments[] = [
'filename' => $name,
'content' => base64_encode(file_get_contents(__DIR__ . '/files/' . $name)),
'content_type' => $type,
];
}
send_email([
'from' => 'Acme Billing <billing@acme.com>',
'to' => ['sam@example.com'],
'subject' => 'Invoice 1042',
'text' => 'Your invoice and our terms are attached.',
'attachments' => $attachments,
], 'invoice-1042');
The second argument is an idempotency key: if the request times out and you retry, the API returns the first response instead of sending twice.
Option 2: PHPMailer over SMTP
composer require phpmailer/phpmailer
<?php
require __DIR__ . '/vendor/autoload.php';
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
$mail = new PHPMailer(true); // true = throw exceptions
try {
$mail->isSMTP();
$mail->Host = 'smtp.mailcandor.com';
$mail->SMTPAuth = true;
$mail->Username = 'mailcandor';
$mail->Password = getenv('MAILCANDOR_KEY');
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 465;
$mail->setFrom('billing@acme.com', 'Acme Billing');
$mail->addAddress('sam@example.com');
$mail->addReplyTo('support@acme.com');
$mail->isHTML(true);
$mail->Subject = 'Invoice 1042';
$mail->Body = '<p>Your invoice is <b>attached</b>.</p>';
$mail->AltBody = 'Your invoice is attached.';
$mail->addAttachment(__DIR__ . '/files/invoice-1042.pdf');
$mail->addAttachment(__DIR__ . '/files/terms.pdf');
$mail->send();
} catch (Exception $e) {
error_log('Mail failed: ' . $mail->ErrorInfo);
}
For port 587, use PHPMailer::ENCRYPTION_STARTTLS instead of ENCRYPTION_SMTPS. Mixing them up is the most common PHPMailer error; the SMTP ports guide explains the difference. Set $mail->SMTPDebug = 2; while testing to see the full SMTP conversation.
The same code works with Gmail (smtp.gmail.com and an app password) for testing, but Gmail is not meant for site email.
A safe contact form script
A form handler that sends email is a favorite target for spammers. This version validates input, sends only to your own address, and keeps the visitor’s address in reply-to:
<?php
// contact.php
require __DIR__ . '/send_email.php'; // the function from Option 1
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$message = trim((string) filter_input(INPUT_POST, 'message'));
$honeypot = (string) filter_input(INPUT_POST, 'website');
if (!$email || $message === '' || strlen($message) > 5000 || $honeypot !== '') {
http_response_code(400);
exit('Please check the form and try again.');
}
send_email([
'from' => 'Contact form <forms@acme.com>',
'to' => 'team@acme.com',
'reply_to' => $email,
'subject' => 'Contact form message',
'text' => $message,
]);
header('Location: /thanks.html', true, 303);
Never put form fields into mail headers directly, and never let the form choose the recipient. Sending the message as text avoids HTML injection.
Common errors
PHPMailer’s SMTP connect() failed usually means a blocked port or a TLS mode that does not match the port. SMTP Error: Could not authenticate means the username or password is wrong. With cURL, a status other than 202 comes with a JSON error whose message and field say what to fix.
Using a framework or CMS?
Laravel and Symfony have their own mailers configured by environment variables. WordPress uses PHPMailer under the hood; see the WordPress SMTP guide.
Which should you choose?
| Email API (cURL) | PHPMailer (SMTP) | mail() | |
|---|---|---|---|
| Packages | None | phpmailer/phpmailer | None |
| Authenticated sending | Yes | Yes | No |
| Safe retries | Idempotency keys | Not built in | No |
| Delivery events | Webhooks per email id | Usually none | No |
| Works on shared hosting | Yes, if outbound HTTPS is allowed | Yes, if SMTP ports are open | Depends on host |
Some shared hosts block outbound SMTP ports. If PHPMailer times out on 465 and 587, the API route over port 443 usually still works.
Before you send: verify your domain
Whichever method you choose, the domain in your from address needs SPF, DKIM and DMARC records. Add it with your provider, publish the DNS records it gives you, and wait for verification. The SPF, DKIM and DMARC guide explains each record.