Tutorial
Invia email con PHP
Invia email da qualsiasi app PHP con l’SDK emailit/emailit-php, con il semplice cURL o con PHPMailer via SMTP, e verifica le firme dei webhook di Emailit.
Questa guida spiega come inviare email da un’applicazione PHP senza framework: con l’SDK ufficiale emailit/emailit-php, con il semplice cURL o via SMTP con PHPMailer. Mostra anche un endpoint webhook che verifica le firme. Usi Laravel? Segui invece la guida per Laravel.
Prerequisiti
- PHP 8.1 o versioni successive e Composer.
- Un dominio di invio verificato, ad esempio
acme.com. - Una chiave API. Basta una chiave di solo invio limitata al tuo dominio.
- Finché il workspace non ha l’accesso alla produzione, puoi inviare solo agli indirizzi email degli account dei membri del workspace.
Installa l’SDK
composer require emailit/emailit-phpL’SDK usa Guzzle per l’HTTP, che Composer installa per te.
Configura la chiave API
Imposta la chiave come variabile d’ambiente nel server web, nel pool PHP-FPM o nel pannello di hosting, e leggila in fase di esecuzione:
export EMAILIT_API_KEY=secret_••••••••••••••••••••••••••••••••$apiKey = getenv('EMAILIT_API_KEY');Se carichi un file .env con un pacchetto come vlucas/phpdotenv, tieni quel file fuori dalla web root e fuori dal controllo di versione.
Invia un’email
require __DIR__.'/vendor/autoload.php';
$emailit = Emailit::client(getenv('EMAILIT_API_KEY'));
$email = $emailit->emails()->send([
'from' => 'Acme <hello@acme.com>',
'to' => 'ada@example.com',
'subject' => 'Your receipt from Acme',
'html' => '<p>Thanks for your order.</p>',
'text' => 'Thanks for your order.',
]);
echo $email->id; // em_…La stessa chiamata accetta cc, bcc, reply_to, attachments, template con variables, scheduled_at e tracking. Per allegare un file, codificalo in base64:
$email = $emailit->emails()->send([
'from' => 'Acme Billing <billing@acme.com>',
'to' => 'ada@example.com',
'subject' => 'Invoice INV-1042',
'html' => '<p>Your invoice is attached.</p>',
'attachments' => [[
'filename' => 'INV-1042.pdf',
'content' => base64_encode(file_get_contents(__DIR__.'/INV-1042.pdf')),
'content_type' => 'application/pdf',
]],
]);Vedi Invia un’email per tutti i campi e Allegati per i limiti.
Gestisci gli errori
use Emailit\Exceptions\ApiErrorException;
use Emailit\Exceptions\AuthenticationException;
use Emailit\Exceptions\RateLimitException;
use Emailit\Exceptions\UnprocessableEntityException;
try {
$emailit->emails()->send($message);
} catch (AuthenticationException $e) {
// 401: the API key is missing or invalid
} catch (RateLimitException $e) {
// 429: wait and retry
} catch (UnprocessableEntityException $e) {
// 422: for example, the from domain isn't verified
} catch (ApiErrorException $e) {
error_log('Emailit error '.$e->getHttpStatus().': '.$e->getMessage());
}Invia senza l’SDK
Se non puoi usare Composer, chiama l’API con cURL:
$ch = curl_init('https://api.emailit.com/v2/emails');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer '.getenv('EMAILIT_API_KEY'),
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'from' => 'Acme <hello@acme.com>',
'to' => 'ada@example.com',
'subject' => 'Your receipt from Acme',
'html' => '<p>Thanks for your order.</p>',
]),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($status >= 400) {
throw new RuntimeException("Emailit returned $status: $body");
}
$email = json_decode($body, true); // $email['id'] is the em_ IDInvia con SMTP
Funziona qualsiasi libreria di posta PHP che supporti SMTP. Con PHPMailer (composer require phpmailer/phpmailer):
use PHPMailer\PHPMailer\PHPMailer;
require __DIR__.'/vendor/autoload.php';
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.emailit.com';
$mail->Port = 587;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->SMTPAuth = true;
$mail->Username = 'emailit';
$mail->Password = getenv('EMAILIT_API_KEY');
$mail->setFrom('hello@acme.com', 'Acme');
$mail->addAddress('ada@example.com');
$mail->Subject = 'Your receipt from Acme';
$mail->isHTML(true);
$mail->Body = '<p>Thanks for your order.</p>';
$mail->AltBody = 'Thanks for your order.';
$mail->send();Con Symfony Mailer, usa il DSN smtp://emailit:API_KEY@smtp.emailit.com:587. Per il TLS implicito usa la porta 465 (PHPMailer::ENCRYPTION_SMTPS); se il tuo host blocca la 587, prova la 2525 o la 2587. Vedi Impostazioni SMTP.
Ricevi i webhook
Crea un webhook che punta al tuo endpoint e salva il suo secret di firma in EMAILIT_WEBHOOK_SECRET. Leggi il corpo grezzo da php://input e verificalo prima di fidarti del contenuto:
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_EMAILIT_SIGNATURE'] ?? '';
$timestamp = $_SERVER['HTTP_X_EMAILIT_TIMESTAMP'] ?? '';
$secret = getenv('EMAILIT_WEBHOOK_SECRET');
$expected = hash_hmac('sha256', $timestamp.'.'.$payload, $secret);
if (abs(time() - (int) $timestamp) > 300 || ! hash_equals($expected, $signature)) {
http_response_code(401);
exit('Invalid signature');
}
// The body is a JSON array of up to 100 events.
foreach (json_decode($payload, true) as $event) {
if ($event['type'] === 'email.bounced') {
$address = $event['data']['object']['to'];
// Stop emailing $address.
}
}
http_response_code(200);Rispondi entro 30 secondi con un 2xx; qualsiasi altra risposta viene ritentata. Vedi Firma delle richieste.
Consigli per la produzione
- Riutilizza un unico client per richiesta o per worker invece di crearne uno per ogni email.
- Invia in background. Per gli invii massivi, metti i messaggi in una coda e inviali da un worker, così le pagine restano veloci e resti entro i limiti di invio (2 email al secondo per impostazione predefinita).
- Rendi sicuri i nuovi tentativi. Se ritenti dopo un timeout, invia un header
Idempotency-Keycon cURL, così l’email non viene inviata due volte. Vedi Idempotenza. - Tieni le chiavi fuori dalla web root. Non fare mai il commit di chiavi o file
.env, e usa una chiave separata per ogni app.