Guide · PHP
How to send email with PHP
Send email from plain PHP with cURL and the Stack Emails API, or with PHPMailer over SMTP, instead of the unreliable mail() function.
Last reviewed November 2026
1. Set up
You need a Stack Emails API key (create one free) and a verified sending domain.
Set the key in your server environment (or .env loaded by your framework):
export STACKEMAILS_API_KEY=se_live_xxxxxxxxxxxx
2. Send your first email
<?php
$payload = [
"from" => "Acme <hello@mail.acme.com>",
"to" => "ada@example.com",
"subject" => "Welcome to Acme",
"html" => "<p>Thanks for signing up!</p>",
];
$ch = curl_init("https://stackemails.com/v1/emails");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("STACKEMAILS_API_KEY"),
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_TIMEOUT => 10,
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($body, true);
if ($status >= 300) {
throw new RuntimeException($data["error"]["message"] ?? "Send failed");
}
echo "Queued " . $data["id"];
A successful request returns 202 with the message id, for example { "id": "msg_5b1f0c6c2a8e4e0f", "status": "queued" }. Errors return a JSON body with error.code and error.message (see errors).
3. Or send over SMTP with PHPMailer
<?php
// composer require phpmailer/phpmailer
use PHPMailer\PHPMailer\PHPMailer;
require "vendor/autoload.php";
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = "smtp.stackemails.com";
$mail->Port = 465;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->SMTPAuth = true;
$mail->Username = "stackemails";
$mail->Password = getenv("STACKEMAILS_API_KEY");
$mail->setFrom("hello@mail.acme.com", "Acme");
$mail->addAddress("ada@example.com");
$mail->isHTML(true);
$mail->Subject = "Welcome to Acme";
$mail->Body = "<p>Thanks for signing up!</p>";
$mail->send();
Production checklist
- Keep the API key in an environment variable or secret manager, never in client-side code.
- Add an
Idempotency-Keyheader to retries so a timeout never sends twice (idempotency). - Subscribe to webhooks for bounces and complaints.
- Check your domain's SPF, DKIM and DMARC records.
- Start from a tested email template for password resets, receipts and invites.