Prerequisites
To get the most out of this guide, you’ll need to:- Create a SendPost Account
- Laravel 9+
- PHP 8.1+
- A Sub-Account API Key from your SendPost dashboard
You can find your API keys in your SendPost Dashboard. Make sure to use your Sub-Account API Key for sending emails.
1. Install Dependencies
composer
composer require sendpost/php-sdk
2. Environment Setup
Add to your.env file:
SENDPOST_API_KEY=your_sub_account_api_key
SENDPOST_FROM_EMAIL=hello@playwithsendpost.io
SENDPOST_FROM_NAME="SendPost"
MAIL_MAILER=sendpost
3. Create SendPost Mail Driver
Createapp/Mail/Drivers/SendPostTransport.php:
PHP
<?php
namespace App\Mail\Drivers;
use Illuminate\Mail\Transport\Transport;
use Swift_Mime_SimpleMessage;
use SendPost\Api\EmailApi;
use SendPost\Model\EmailMessage;
use SendPost\Configuration;
class SendPostTransport extends Transport
{
protected $apiKey;
protected $fromEmail;
protected $fromName;
public function __construct($apiKey, $fromEmail, $fromName)
{
$this->apiKey = $apiKey;
$this->fromEmail = $fromEmail;
$this->fromName = $fromName;
}
public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
{
$this->beforeSendPerformed($message);
$config = Configuration::getDefaultConfiguration();
$config->setApiKey('subAccountAuth', $this->apiKey);
$config->setHost('https://api.sendpost.io/api/v1');
$emailApi = new EmailApi(null, $config);
$emailMessage = new EmailMessage();
// Set sender
$from = $message->getFrom();
if ($from) {
$emailAddress = key($from);
$emailMessage->setFrom([
'email' => $emailAddress,
'name' => $from[$emailAddress] ?? $this->fromName
]);
} else {
$emailMessage->setFrom([
'email' => $this->fromEmail,
'name' => $this->fromName
]);
}
// Set recipients
$to = [];
foreach ($message->getTo() as $email => $name) {
$to[] = [
'email' => $email,
'name' => $name
];
}
$emailMessage->setTo($to);
// Set subject
$emailMessage->setSubject($message->getSubject());
// Set body
$body = $message->getBody();
$emailMessage->setHtmlBody($body);
// Get text version if available
$children = $message->getChildren();
foreach ($children as $child) {
if ($child->getContentType() === 'text/plain') {
$emailMessage->setTextBody($child->getBody());
break;
}
}
// Send email
try {
$response = $emailApi->sendEmail($emailMessage);
return $response;
} catch (\Exception $e) {
throw new \Swift_TransportException($e->getMessage());
}
}
}
4. Register Mail Driver
Add toapp/Providers/AppServiceProvider.php:
PHP
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Mail;
use App\Mail\Drivers\SendPostTransport;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
//
}
public function boot()
{
Mail::extend('sendpost', function (array $config) {
return new SendPostTransport(
config('services.sendpost.api_key'),
config('services.sendpost.from.email'),
config('services.sendpost.from.name')
);
});
}
}
config/services.php:
PHP
'sendpost' => [
'api_key' => env('SENDPOST_API_KEY'),
'from' => [
'email' => env('SENDPOST_FROM_EMAIL'),
'name' => env('SENDPOST_FROM_NAME'),
],
],
config/mail.php:
PHP
'mailers' => [
// ... other mailers ...
'sendpost' => [
'transport' => 'sendpost',
],
],
5. Send Your First Email
Using Mail Facade
PHP
use Illuminate\Support\Facades\Mail;
Mail::raw('Hello, this is a test email!', function ($message) {
$message->to('user@example.com')
->subject('Test Email');
});
Using Mailable Class
Create a mailable:php artisan make:mail WelcomeEmail
app/Mail/WelcomeEmail.php:
PHP
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class WelcomeEmail extends Mailable
{
use Queueable, SerializesModels;
public $user;
public function __construct($user)
{
$this->user = $user;
}
public function build()
{
return $this->subject('Welcome {{firstName}}!')
->view('emails.welcome')
->with([
'firstName' => $this->user->first_name,
]);
}
}
resources/views/emails/welcome.blade.php:
Blade
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
<h1>Welcome, {{ $firstName }}!</h1>
<p>Thank you for joining us. We're excited to have you on board.</p>
<p>Get started by exploring our features:</p>
<ul>
<li>Feature 1</li>
<li>Feature 2</li>
<li>Feature 3</li>
</ul>
<p>If you have any questions, just reply to this email.</p>
<p><a href="{{ $unsubscribeUrl }}">Unsubscribe</a></p>
</body>
</html>
PHP
use App\Mail\WelcomeEmail;
use Illuminate\Support\Facades\Mail;
Mail::to($user->email)->send(new WelcomeEmail($user));
6. Common Use Cases
Password Reset Email
Createapp/Mail/PasswordResetEmail.php:
PHP
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class PasswordResetEmail extends Mailable
{
use Queueable, SerializesModels;
public $user;
public $resetUrl;
public function __construct($user, $token)
{
$this->user = $user;
$this->resetUrl = url("/reset-password?token={$token}");
}
public function build()
{
return $this->subject('Reset Your Password')
->view('emails.password-reset')
->with([
'firstName' => $this->user->first_name,
'resetUrl' => $this->resetUrl,
]);
}
}
resources/views/emails/password-reset.blade.php:
Blade
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Reset Your Password</title>
</head>
<body>
<h2>Hello {{ $firstName }},</h2>
<p>We received a request to reset your password. Click the button below:</p>
<p>
<a href="{{ $resetUrl }}" style="background-color: #5750EC; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; display: inline-block;">
Reset Password
</a>
</p>
<p>Or copy and paste this link: {{ $resetUrl }}</p>
<p>This link will expire in 1 hour.</p>
<p>If you didn't request this, please ignore this email.</p>
</body>
</html>
Order Confirmation Email
Createapp/Mail/OrderConfirmation.php:
PHP
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class OrderConfirmation extends Mailable
{
use Queueable, SerializesModels;
public $order;
public $user;
public function __construct($order, $user)
{
$this->order = $order;
$this->user = $user;
}
public function build()
{
return $this->subject("Order {$this->order->id} Confirmed")
->view('emails.order-confirmation')
->with([
'order' => $this->order,
'user' => $this->user,
]);
}
}
7. Using Notifications
Create a notification:php artisan make:notification WelcomeNotification
app/Notifications/WelcomeNotification.php:
PHP
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class WelcomeNotification extends Notification
{
use Queueable;
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Welcome {{firstName}}!')
->view('emails.welcome', [
'firstName' => $notifiable->first_name,
]);
}
}
PHP
$user->notify(new WelcomeNotification());
8. Personalization with Custom Fields
Create a custom mailable with personalization:PHP
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class PersonalizedEmail extends Mailable
{
use Queueable, SerializesModels;
public $recipient;
public $customFields;
public function __construct($recipient, $customFields = [])
{
$this->recipient = $recipient;
$this->customFields = $customFields;
}
public function build()
{
// For SendPost personalization, you'll need to use the API directly
// or extend the transport to handle customFields
return $this->subject('Personalized Email')
->view('emails.personalized')
->with($this->customFields);
}
}
9. Direct API Usage (Alternative)
Createapp/Services/SendPostService.php:
PHP
<?php
namespace App\Services;
use SendPost\Api\EmailApi;
use SendPost\Model\EmailMessage;
use SendPost\Configuration;
class SendPostService
{
protected $apiKey;
protected $fromEmail;
protected $fromName;
public function __construct()
{
$this->apiKey = config('services.sendpost.api_key');
$this->fromEmail = config('services.sendpost.from.email');
$this->fromName = config('services.sendpost.from.name');
}
public function sendEmail($to, $subject, $htmlBody, $textBody = null, $customFields = [])
{
$config = Configuration::getDefaultConfiguration();
$config->setApiKey('subAccountAuth', $this->apiKey);
$config->setHost('https://api.sendpost.io/api/v1');
$emailApi = new EmailApi(null, $config);
$emailMessage = new EmailMessage();
$emailMessage->setFrom([
'email' => $this->fromEmail,
'name' => $this->fromName
]);
$recipients = [];
if (is_string($to)) {
$recipients[] = [
'email' => $to,
'customFields' => $customFields
];
} else {
foreach ($to as $email => $name) {
$recipients[] = [
'email' => $email,
'name' => $name,
'customFields' => $customFields
];
}
}
$emailMessage->setTo($recipients);
$emailMessage->setSubject($subject);
$emailMessage->setHtmlBody($htmlBody);
if ($textBody) {
$emailMessage->setTextBody($textBody);
}
try {
$response = $emailApi->sendEmail($emailMessage);
return ['success' => true, 'message_id' => $response->getMessageId()];
} catch (\Exception $e) {
return ['success' => false, 'error' => $e->getMessage()];
}
}
}
PHP
use App\Services\SendPostService;
$sendPostService = new SendPostService();
$result = $sendPostService->sendEmail(
'user@example.com',
'Welcome {{firstName}}!',
'<h1>Welcome, {{firstName}}!</h1>',
'Welcome, {{firstName}}!',
['firstName' => 'John']
);
Make sure your sender email domain is verified in your SendPost account before sending emails.
10. Next Steps
Explore more examples and use cases:Laravel Documentation
Learn more about Laravel framework
SendPost PHP SDK
View the official SDK on GitHub
Quickstart Example
View a complete working example on GitHub