Offizielles Laravel-SDK für die E-Mail-API von toSend.
- Paket:
tosend/tosend-laravel - Voraussetzungen: PHP 8.1+, Laravel 10.x, 11.x, 12.x oder 13.x
- Repository: tosend/tosend-laravel
Installation
composer require tosend/tosend-laravel
Konfiguration
Tragen Sie Ihren API-Schlüssel in die Datei .env ein:
TOSEND_API_KEY=tsend_your_api_key
Optional können Sie die Konfigurationsdatei veröffentlichen:
php artisan vendor:publish --tag=tosend-config
Konfigurationsoptionen
// config/tosend.php
return [
'api_key' => env('TOSEND_API_KEY'),
'admin_key' => env('TOSEND_ADMIN_KEY'), // optional, only for the Admin API client
'api_url' => env('TOSEND_API_URL', 'https://api.tosend.com'),
'from' => [
'address' => env('TOSEND_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')),
'name' => env('TOSEND_FROM_NAME', env('MAIL_FROM_NAME')),
],
'timeout' => env('TOSEND_TIMEOUT', 30),
];
Schnellstart
Über die Facade
use ToSend\Laravel\Facades\ToSend;
$response = ToSend::send([
'from' => ['email' => 'hello@yourdomain.com', 'name' => 'Your App'],
'to' => [['email' => 'user@example.com']],
'subject' => 'Welcome!',
'html' => '<h1>Hello World</h1>',
]);
echo $response->messageId;
Über Dependency Injection
use ToSend\Laravel\Contracts\ToSendClient;
class EmailController extends Controller
{
public function send(ToSendClient $tosend)
{
$response = $tosend->send([
'from' => ['email' => 'hello@yourdomain.com'],
'to' => [['email' => 'user@example.com']],
'subject' => 'Hello!',
'html' => '<p>Welcome to our app!</p>',
]);
return $response->messageId;
}
}
E-Mail senden
Über den E-Mail-Builder
use ToSend\Laravel\Facades\ToSend;
use ToSend\Laravel\Data\Email;
use ToSend\Laravel\Data\Attachment;
$email = Email::make(
from: ['email' => 'hello@yourdomain.com', 'name' => 'Your App'],
subject: 'Your Invoice'
)
->to(['email' => 'user@example.com', 'name' => 'John Doe'])
->to('another@example.com')
->cc('manager@example.com')
->bcc(['email' => 'archive@example.com'])
->html('<h1>Invoice Attached</h1>')
->text('Invoice Attached')
->attach(Attachment::fromPath('/path/to/invoice.pdf'));
$response = ToSend::send($email);
Sammelversand
use ToSend\Laravel\Facades\ToSend;
$response = ToSend::batch([
[
'from' => ['email' => 'hello@yourdomain.com'],
'to' => [['email' => 'user1@example.com']],
'subject' => 'Hello User 1',
'html' => '<p>Welcome!</p>',
],
[
'from' => ['email' => 'hello@yourdomain.com'],
'to' => [['email' => 'user2@example.com']],
'subject' => 'Hello User 2',
'html' => '<p>Welcome!</p>',
],
]);
// Check results
echo "Sent: " . $response->successCount();
echo "Failed: " . $response->failedCount();
foreach ($response->results as $result) {
if ($result->isSuccess()) {
echo "Sent: " . $result->messageId;
} else {
echo "Failed: " . $result->message;
}
}
Kontodaten
use ToSend\Laravel\Facades\ToSend;
$info = ToSend::getAccountInfo();
echo $info->id;
echo $info->status; // 'active'
echo $info->creditBalance; // null means the account does not consume credits
echo $info->limitPerSecond;
foreach ($info->domains as $domain) {
echo $domain->domainName . ': ' . $domain->verificationStatus;
}
// Get only verified domains
$verified = $info->verifiedDomains();
Admin-API
ToSend\Laravel\ToSendAdmin ist ein eigener Client für die Admin-API. Er erwartet einen Admin-Schlüssel (tsend_admin_...) und lehnt einen Versandschlüssel schon beim Erzeugen ab. Jeder Aufruf braucht den passenden Scope am Schlüssel. Fehlt einer, wird ein 403 geworfen, dessen getErrorCode() insufficient_scope ist.
Admin-Schlüssel werden auf Ihrem Hauptkonto im Dashboard angelegt, unter API Keys → Admin API. Tragen Sie Ihren Schlüssel in .env ein:
TOSEND_ADMIN_KEY=tsend_admin_your_key
use ToSend\Laravel\ToSendAdmin;
$admin = app(ToSendAdmin::class);
// 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>',
]);
Außerdem verfügbar: getInfo, listDomains, deleteDomain, listEmails, getEmail, listSuppressions, deleteSuppression, listWebhooks, createWebhook, updateWebhook, deleteWebhook, listSendingKeys, deleteSendingKey, listTeams, createTeam, updateTeam und batch. Listenmethoden nehmen page und per_page und liefern data, total, page und per_page. Wird ToSendAdmin aufgelöst, ohne dass TOSEND_ADMIN_KEY gesetzt ist, gibt es eine ToSendException; der Versandclient ist davon nicht betroffen.
Laravel-Mail-Anbindung
Nutzen Sie toSend als Standard-Mailer von Laravel.
Mailer einrichten
MAIL_MAILER=tosend
TOSEND_API_KEY=tsend_your_api_key
TOSEND_FROM_ADDRESS=hello@yourdomain.com
TOSEND_FROM_NAME="Your App"
// config/mail.php
'mailers' => [
'tosend' => [
'transport' => 'tosend',
],
],
Mit Laravel Mail senden
use Illuminate\Support\Facades\Mail;
// Using a Mailable
Mail::to('user@example.com')->send(new WelcomeEmail());
// Using a specific mailer
Mail::mailer('tosend')
->to('user@example.com')
->send(new WelcomeEmail());
Ein Mailable anlegen
namespace App\Mail;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Mail\Mailables\Attachment;
class WelcomeEmail extends Mailable
{
public function envelope(): Envelope
{
return new Envelope(
from: new \Illuminate\Mail\Mailables\Address('hello@yourdomain.com', 'Your App'),
subject: 'Welcome to Our App',
);
}
public function content(): Content
{
return new Content(
view: 'emails.welcome',
);
}
public function attachments(): array
{
return [
Attachment::fromPath('/path/to/file.pdf'),
];
}
}
Anhänge
Aus einem Dateipfad
use ToSend\Laravel\Data\Attachment;
$attachment = Attachment::fromPath('/path/to/document.pdf');
// With custom name and type
$attachment = Attachment::fromPath(
path: '/path/to/document.pdf',
name: 'custom-name.pdf',
type: 'application/pdf'
);
Aus Inhalt
$attachment = Attachment::fromContent(
content: $pdfContent,
name: 'report.pdf',
type: 'application/pdf'
);
Aus Base64
$attachment = Attachment::fromBase64(
base64Content: $base64String,
name: 'image.png',
type: 'image/png'
);
Fehlerbehandlung
use ToSend\Laravel\Facades\ToSend;
use ToSend\Laravel\Exceptions\ToSendException;
try {
$response = ToSend::send([
'from' => ['email' => 'hello@yourdomain.com'],
'to' => [['email' => 'user@example.com']],
'subject' => 'Hello',
'html' => '<p>Hello</p>',
]);
} catch (ToSendException $e) {
// Get error message
echo $e->getMessage();
// Get HTTP status code
echo $e->getCode();
// Get validation errors
$errors = $e->getErrors();
// Check error type
if ($e->isValidationError()) {
// Handle validation error (422)
}
if ($e->isAuthenticationError()) {
// Handle auth error (401/403)
}
if ($e->isRateLimitError()) {
// Handle rate limit (429)
}
}
Tests
Mocken Sie den toSend-Client in Ihren Tests:
use ToSend\Laravel\Contracts\ToSendClient;
use ToSend\Laravel\Data\EmailResponse;
public function test_sends_welcome_email()
{
$mock = $this->mock(ToSendClient::class);
$mock->shouldReceive('send')
->once()
->andReturn(new EmailResponse(messageId: 'test-message-id'));
// Your test code...
}
Oder nutzen Sie eine eigene Basis-URL für Tests:
# .env.testing
TOSEND_API_URL=http://localhost:8080