Send email from Laravel with Shipmail
Add Shipmail as a Laravel mail transport. Your Mailables, notifications and Mail::to() calls then send through the Shipmail API without other changes.
Last updated
Before you start
- A verified sending subdomain, such as
notify.example.com, with an active sender. See Transactional email. - An API key with send access to the sender's mailbox.
- The sender address, such as
hello@notify.example.com. Use the bare address. Shipmail adds the sender name.
Add the transport
Save it as app/Mail/ShipmailTransport.php. It sends the bare From address, because Shipmail adds the sender name. throw() raises an exception if Shipmail refuses the send.
<?php
namespace App\Mail;
use Illuminate\Support\Facades\Http;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\Transport\AbstractTransport;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\MessageConverter;
class ShipmailTransport extends AbstractTransport
{
public function __construct(protected string $key)
{
parent::__construct();
}
protected function doSend(SentMessage $message): void
{
$email = MessageConverter::toEmail($message->getOriginalMessage());
$addresses = fn (array $list) => array_map(
fn (Address $address) => $address->getAddress(),
$list,
);
Http::withToken($this->key)
->post('https://shipmail.to/api/v1/messages', array_filter([
'from' => $email->getFrom()[0]->getAddress(),
'to' => $addresses($email->getTo()),
'cc' => $addresses($email->getCc()),
'bcc' => $addresses($email->getBcc()),
'subject' => $email->getSubject(),
'html' => $email->getHtmlBody(),
'text' => $email->getTextBody(),
]))
->throw();
}
public function __toString(): string
{
return 'shipmail';
}
}Register it
// app/Providers/AppServiceProvider.php
use App\Mail\ShipmailTransport;
use Illuminate\Support\Facades\Mail;
public function boot(): void
{
Mail::extend('shipmail', function (array $config = []) {
return new ShipmailTransport($config['key']);
});
}// config/mail.php, in 'mailers'
'shipmail' => [
'transport' => 'shipmail',
'key' => env('SHIPMAIL_API_KEY'),
],Make it the default mailer
Set the mailer and the sender address in .env.
MAIL_MAILER=shipmail
MAIL_FROM_ADDRESS=hello@notify.example.com
SHIPMAIL_API_KEY=sm_live_...Existing code sends through Shipmail with no change:
Mail::to($user)->send(new WelcomeMail($user));Test without sending
Use a sm_test_ key while you build. Shipmail accepts the request, delivers nothing and lists the send under Test in Activity. See Sandbox mode.