SDK PHP ufficiale per l’API email di toSend.
- Pacchetto:
tosend/tosend-php - Requisiti: PHP 7.4+, estensione cURL
- Repository: tosend/tosend-php
Installazione
Con Composer
composer require tosend/tosend-php
Senza Composer
L’SDK non ha dipendenze esterne, quindi puoi usarlo senza Composer:
- Scarica
src/Api.phpesrc/ToSendException.php(piùsrc/AdminApi.phpper l’Admin API) - Mettili dove vuoi nel progetto
- Includili nel codice:
require_once 'path/to/ToSendException.php';
require_once 'path/to/Api.php';
$tosend = new ToSend\Api('tsend_your_api_key');
Avvio rapido
use ToSend\Api;
$tosend = new Api('tsend_your_api_key');
$response = $tosend->send([
'from' => [
'email' => 'hello@yourdomain.com',
'name' => 'Your App'
],
'to' => [
['email' => 'user@example.com']
],
'subject' => 'Hello from toSend!',
'html' => '<h1>Welcome!</h1><p>Thanks for signing up.</p>'
]);
echo $response['message_id'];
Configurazione
Semplice
$tosend = new ToSend\Api('tsend_your_api_key');
URL di base personalizzato
$tosend = new ToSend\Api('tsend_your_api_key');
$tosend->setBaseUrl('https://custom-api.example.com');
Invio di un’email
Email di base
$response = $tosend->send([
'from' => [
'email' => 'hello@yourdomain.com',
'name' => 'Your App' // optional
],
'to' => [
['email' => 'user@example.com'],
['email' => 'another@example.com', 'name' => 'John Doe']
],
'subject' => 'Welcome!',
'html' => '<h1>Hello</h1>',
'text' => 'Hello' // optional, auto-generated from HTML if not provided
]);
Con CC, BCC e Reply-To
$response = $tosend->send([
'from' => ['email' => 'hello@yourdomain.com'],
'to' => [['email' => 'user@example.com']],
'cc' => [['email' => 'cc@example.com']],
'bcc' => [['email' => 'bcc@example.com']],
'reply_to' => ['email' => 'support@yourdomain.com', 'name' => 'Support'],
'subject' => 'Hello',
'html' => '<p>Hello World</p>'
]);
Con allegati
$response = $tosend->send([
'from' => ['email' => 'hello@yourdomain.com'],
'to' => [['email' => 'user@example.com']],
'subject' => 'Your Invoice',
'html' => '<p>Please find your invoice attached.</p>',
'attachments' => [
[
'type' => 'application/pdf',
'name' => 'invoice.pdf',
'content' => base64_encode(file_get_contents('invoice.pdf'))
]
]
]);
Invio in batch
Invia più email in una sola richiesta:
$response = $tosend->batch([
[
'from' => ['email' => 'hello@yourdomain.com'],
'to' => [['email' => 'user1@example.com']],
'subject' => 'Hello User 1',
'html' => '<p>Hello!</p>'
],
[
'from' => ['email' => 'hello@yourdomain.com'],
'to' => [['email' => 'user2@example.com']],
'subject' => 'Hello User 2',
'html' => '<p>Hello!</p>'
]
]);
foreach ($response['results'] as $result) {
if ($result['status'] === 'success') {
echo "Sent: " . $result['message_id'] . "\n";
} else {
echo "Failed: " . $result['message'] . "\n";
}
}
Informazioni sull’account
$info = $tosend->getAccountInfo();
echo "Status: " . $info['account']['status'] . "\n";
echo "Credits: " . ($info['account']['credit_balance'] ?? 'unlimited') . "\n";
foreach ($info['domains'] as $domain) {
echo $domain['domain_name'] . ": " . $domain['verification_status'] . "\n";
}
Gestione degli errori
use ToSend\Api;
use ToSend\ToSendException;
try {
$response = $tosend->send([
'from' => ['email' => 'hello@yourdomain.com'],
'to' => [['email' => 'user@example.com']],
'subject' => 'Hello',
'html' => '<p>Hello</p>'
]);
} catch (ToSendException $e) {
echo "Error: " . $e->getMessage() . "\n";
echo "Code: " . $e->getCode() . "\n";
// Get detailed validation errors (a string per field, or an array of messages)
foreach ($e->getErrors() as $field => $messages) {
foreach ((array) $messages as $message) {
echo "$field: $message\n";
}
}
}
Admin API
ToSend\AdminApi è un client separato per l’Admin API. Prende una chiave di amministrazione (tsend_admin_...) e rifiuta una chiave di invio quando crei il client. Ogni chiamata richiede lo scope corrispondente sulla chiave.
$admin = new \ToSend\AdminApi(getenv('TOSEND_ADMIN_KEY'));
// Act on one of your client teams (sends X-Account-Id)
$client = $admin->forAccount(4203);
$domain = $client->createDomain('client.example.com');
$detail = $client->getDomain($domain['id']);
print_r($detail['dns_records']['dkim']); // show these records to your client
// Needs api_keys:write and emails:send
$key = $client->createSendingKey('Client: Acme Corp');
echo $key['api_key']; // returned once, store it now
// Needs emails:send
$client->send([
'from' => ['email' => 'hello@client.example.com'],
'to' => [['email' => 'user@example.com']],
'subject' => 'Hi',
'html' => '<p>Hello</p>',
]);
Disponibili anche: getInfo (controlla la chiave ed elenca i suoi scope), listDomains, deleteDomain, listEmails, getEmail, listSuppressions, deleteSuppression, listWebhooks, createWebhook, updateWebhook, deleteWebhook, listSendingKeys, deleteSendingKey, listTeams, createTeam, updateTeam e batch. I metodi di elenco prendono page e per_page e restituiscono data, total, page e per_page.
Riferimento API
new Api(string $apiKey)
Crea una nuova istanza di Api con la tua chiave API.
send(array $params): array
Invia una singola email. In caso di successo restituisce ['message_id' => '...'].
Parametri:
from(obbligatorio) - Indirizzo del mittente['email' => '...', 'name' => '...']to(obbligatorio) - Array di indirizzi destinatariosubject(obbligatorio) - Oggetto dell’emailhtml(obbligatorio setextnon è impostato) - Contenuto HTMLtext(facoltativo) - Contenuto in testo semplice, generato dahtmlse omessocc(facoltativo) - Array di indirizzi CCbcc(facoltativo) - Array di indirizzi BCCreply_to(facoltativo) - Indirizzo di rispostaattachments(facoltativo) - Array di allegati
batch(array $emails): array
Invia più email. Restituisce ['results' => [...]] con lo stato di ogni email.
getAccountInfo(): array
Ottiene le informazioni sull’account e sui domini.
setBaseUrl(string $url): self
Imposta un URL di base API personalizzato (utile per i test).