How to Send Email in PHP: PHPMailer, Laravel and API
Pranav Patel
Co-founderยท13 min read
On this page

Send email from PHP with PHPMailer, Laravel, Symfony Mailer or WordPress, or with an email API. Copy-paste examples for HTML email, attachments, queued sending and retries without duplicates.
PHP has a built-in mail() function, but you should not use it for real email. Send through a provider instead: over SMTP with PHPMailer or your framework's mailer, or over HTTPS with an email API SDK.
This guide covers PHPMailer, the Reloop PHP SDK, Laravel, Symfony and WordPress, then the production details: attachments, queued sending and safe retries.
Working in another language? See how to send email in Python or Node.js.
Which approach should you use?
composer require phpmailer/phpmailercomposer require reloop/reloop-emailPHPMailer properties, MIME handled for youhtml, text, attachmentsPHPMailer\PHPMailer\Exception with a text messageReloopApiException with status and JSON bodyMail and WordPress wp_mailIf you are wiring up Laravel's notifications, password resets or a WordPress plugin, use SMTP settings. If you are writing the send call yourself, use the API.
Prerequisites
- PHP 8.1 or later and Composer
- A verified sending domain with SPF, DKIM and DMARC
- An API key from the Reloop dashboard. Keys start with
rl_, and the same key works for the API and SMTP.
export RELOOP_API_KEY=rl_your_api_keyKeep the key in the environment or a secrets manager, never in your code or git.
Why not PHP's mail() function?
mail() hands the message to the local sendmail binary and returns true if that worked. It does not tell you whether the email was delivered, accepted or rejected. On most servers it also means:
- No authentication. The message is not DKIM-signed for your domain, so Gmail and Outlook treat it as suspicious or reject it under the 2024 sender rules.
- Your server's IP sends the mail. Shared hosting and cloud IPs often have a poor reputation or sit on blocklists.
- You build headers by hand. Concatenating user input into headers invites header injection.
- It is often disabled. Many hosts and Docker images ship without a working
sendmail.
Use SMTP with PHPMailer or an API instead. Both authenticate to a provider that signs and delivers the message.
Method 1: Send email with PHPMailer
Install
composer require phpmailer/phpmailerSend an email
1<?php2
3require __DIR__ . '/vendor/autoload.php';4
5use PHPMailer\PHPMailer\PHPMailer;6
7$mail = new PHPMailer(true); // true: throw exceptions on errors8
9$mail->isSMTP();10$mail->Host = 'smtp.reloop.sh';11$mail->Port = 587;12$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;13$mail->SMTPAuth = true;14$mail->Username = 'reloop';15$mail->Password = getenv('RELOOP_API_KEY');16$mail->Timeout = 30;17$mail->CharSet = PHPMailer::CHARSET_UTF8;18
19$mail->setFrom('hello@mail.acme.com', 'Acme');20$mail->addAddress('user@example.com');21
22$mail->isHTML(true);23$mail->Subject = 'Welcome to Acme';24$mail->Body = '<h1>Welcome!</h1><p>Thanks for signing up.</p>';25$mail->AltBody = 'Welcome! Thanks for signing up.';26
27$mail->send();The username can be any string. The password is your API key. AltBody is the plain-text version, and PHPMailer builds the multipart message for you. Set CharSet to UTF-8: PHPMailer defaults to ISO-8859-1, which mangles names and emoji.
When port 587 is blocked
Some hosts block outbound 587. Reloop also accepts STARTTLS on port 2587 (and 2025), so only the port number changes:
$mail->Port = 2587;$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;Reloop does not offer implicit TLS on port 465, so do not use PHPMailer::ENCRYPTION_SMTPS with it. If the connection hangs or times out, see SMTP ports explained.
Handle SMTP errors
1use PHPMailer\PHPMailer\Exception;2use PHPMailer\PHPMailer\SMTP;3
4try {5 $mail->send();6} catch (Exception $e) {7 error_log('Send failed: ' . $mail->ErrorInfo);8}PHPMailer uses one exception class for everything, so the reason is in the message: Could not authenticate means a wrong API key, and Could not connect to SMTP host means a blocked port or a TLS mismatch. To see the full SMTP conversation while debugging, set $mail->SMTPDebug = SMTP::DEBUG_SERVER; and turn it off again before you deploy.
Can I send with Gmail from PHP?
For a personal script, yes: use smtp.gmail.com on port 587 with an App Password. For an app, no. Gmail limits personal accounts to about 500 recipients a day, every message comes from your @gmail.com address, and bulk sending gets the account suspended.
Method 2: Send email with the PHP SDK
Install
composer require reloop/reloop-emailThe SDK needs PHP 8.1 or later and uses Guzzle 7 for HTTP.
Send an email
1<?php2
3require __DIR__ . '/vendor/autoload.php';4
5use Reloop\Exceptions\ReloopApiException;6use Reloop\Exceptions\ReloopValidationException;7use Reloop\Reloop;8
9$reloop = Reloop::client(getenv('RELOOP_API_KEY'));10
11try {12 $result = $reloop->mail->send([13 'from' => 'Acme <hello@mail.acme.com>',14 'to' => 'user@example.com',15 'subject' => 'Welcome to Acme',16 'html' => '<h1>Welcome!</h1><p>Thanks for signing up.</p>',17 'text' => 'Welcome! Thanks for signing up.',18 ]);19 echo 'Sent: ' . $result['id'] . PHP_EOL;20} catch (ReloopValidationException $e) {21 // Bad input, caught before any request was made22 error_log("Invalid {$e->field}: {$e->getMessage()}");23} catch (ReloopApiException $e) {24 error_log("Failed: {$e->status} {$e->getMessage()}");25}send() returns the decoded JSON response as an array, with the email ID in id. The SDK throws on failure:
ReloopValidationExceptionwhen a required field (from,to,subject) is missing. No request is sent.ReloopApiExceptionfor any non-2xx response or network failure.$e->statusis the HTTP status, or0for a network error, and$e->bodyholds the API's JSON error withmessage,whyandfix.
Reloop::client() creates a Guzzle client with a 30-second timeout. Create it once and reuse it, for example as a singleton in your framework's container.
Send to several recipients
1$reloop->mail->send([2 'from' => 'Acme <hello@mail.acme.com>',3 'to' => ['ada@example.com', 'grace@example.com'],4 'cc' => 'team@acme.com',5 'reply_to' => 'support@acme.com',6 'subject' => 'Your weekly report',7 'text' => 'Here is your report.',8 'tags' => [['name' => 'type', 'value' => 'weekly_report']],9]);Every address in to sees the others. For personalized mail, send one message per recipient.
Send a stored template
Keep copy out of your code so non-developers can edit it. Create the template in Reloop, then send it by ID with variables:
1$reloop->mail->send([2 'from' => 'Acme <hello@mail.acme.com>',3 'to' => 'user@example.com',4 'subject' => 'Welcome to Acme',5 'template' => [6 'id' => 'tmpl_welcome',7 'variables' => ['first_name' => 'Ada', 'plan' => 'Pro'],8 ],9]);The SDK checks for subject before sending, so pass one even when the template has its own. See templates for variables and defaults.
Laravel
SMTP settings
Laravel's Mail facade works with any SMTP provider. Set these in .env and Mailables, notifications and password reset emails all go through Reloop:
1# .env2MAIL_MAILER=smtp3MAIL_SCHEME=smtp4MAIL_HOST=smtp.reloop.sh5MAIL_PORT=5876MAIL_USERNAME=reloop7MAIL_PASSWORD=rl_your_api_key8MAIL_FROM_ADDRESS=hello@mail.acme.com9MAIL_FROM_NAME="Acme"These map to the smtp mailer that ships in config/mail.php, so you do not need to edit that file:
1// config/mail.php (default, shown for reference)2'smtp' => [3 'transport' => 'smtp',4 'scheme' => env('MAIL_SCHEME'),5 'url' => env('MAIL_URL'),6 'host' => env('MAIL_HOST', '127.0.0.1'),7 'port' => env('MAIL_PORT', 2525),8 'username' => env('MAIL_USERNAME'),9 'password' => env('MAIL_PASSWORD'),10 'timeout' => null,11 'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),12],Keep the scheme as smtp, never smtps. The smtp scheme connects in plain text and upgrades with STARTTLS, which is what Reloop expects. If 587 is blocked, set MAIL_PORT=2587. On Laravel 10 and earlier, the setting is MAIL_ENCRYPTION=tls instead of MAIL_SCHEME.
Mailables
Generate a Mailable with php artisan make:mail WelcomeMail, then define its subject and views:
1<?php2
3namespace App\Mail;4
5use App\Models\User;6use Illuminate\Bus\Queueable;7use Illuminate\Mail\Mailable;8use Illuminate\Mail\Mailables\Content;9use Illuminate\Mail\Mailables\Envelope;10use Illuminate\Queue\SerializesModels;11
12class WelcomeMail extends Mailable13{14 use Queueable, SerializesModels;15
16 public function __construct(public User $user)17 {18 }19
20 public function envelope(): Envelope21 {22 return new Envelope(subject: 'Welcome to Acme');23 }24
25 public function content(): Content26 {27 return new Content(28 view: 'emails.welcome',29 text: 'emails.welcome-text',30 );31 }32}1use App\Mail\WelcomeMail;2use Illuminate\Support\Facades\Mail;3
4Mail::to($user)->send(new WelcomeMail($user));Public properties like $user are available in the Blade views. The text view gives you a plain-text part next to the HTML.
Queue it
Sending inside the request adds a full SMTP round trip to your response time. Queue the Mailable instead:
Mail::to($user)->queue(new WelcomeMail($user));Or add implements ShouldQueue to the class so every send() is queued. Set QUEUE_CONNECTION to database or redis and run php artisan queue:work. With the default sync connection, "queued" mail still sends inside the request.
A queued Mailable can set public $tries = 3; and a backoff() method. Be aware that SMTP has no idempotency key, so a retry after a timeout can send the email twice. For mail that must go out exactly once, use the API with a job (below).
Using the SDK in Laravel
Add the key to config/services.php and bind one client in a service provider:
1'reloop' => [2 'key' => env('RELOOP_API_KEY'),3],1use Reloop\Reloop;2
3public function register(): void4{5 $this->app->singleton(6 Reloop::class,7 fn () => Reloop::client(config('services.reloop.key')),8 );9}Then type-hint Reloop anywhere Laravel resolves dependencies, such as a controller:
1<?php2
3namespace App\Http\Controllers;4
5use Illuminate\Http\JsonResponse;6use Illuminate\Http\Request;7use Reloop\Exceptions\ReloopApiException;8use Reloop\Reloop;9
10class ContactController extends Controller11{12 public function store(Request $request, Reloop $reloop): JsonResponse13 {14 $data = $request->validate([15 'email' => ['required', 'email'],16 'message' => ['required', 'string', 'max:5000'],17 ]);18
19 try {20 $result = $reloop->mail->send([21 'from' => 'Acme Website <contact@mail.acme.com>',22 'to' => 'support@acme.com',23 'reply_to' => $data['email'],24 'subject' => "New message from {$data['email']}",25 'text' => $data['message'],26 ]);27 } catch (ReloopApiException $e) {28 report($e);29
30 return response()->json(['error' => 'Could not send message'], 502);31 }32
33 return response()->json(['id' => $result['id']]);34 }35}The visitor's address goes in reply_to, never in from. You can only send from your verified domain, and putting someone else's domain in from fails DMARC.
Symfony
Symfony Mailer reads one DSN from the environment:
MAILER_DSN=smtp://reloop:rl_your_api_key@smtp.reloop.sh:587The smtp:// scheme upgrades to STARTTLS automatically when the server offers it, which Reloop always does. On Symfony 7.1 or later, add ?require_tls=true to refuse to send if TLS is not available. Do not use smtps://, which means implicit TLS. If 587 is blocked, change the port to 2587.
1<?php2
3namespace App\Controller;4
5use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;6use Symfony\Component\HttpFoundation\Response;7use Symfony\Component\Mailer\MailerInterface;8use Symfony\Component\Mime\Address;9use Symfony\Component\Mime\Email;10use Symfony\Component\Routing\Attribute\Route;11
12class WelcomeController extends AbstractController13{14 #[Route('/welcome', methods: ['POST'])]15 public function send(MailerInterface $mailer): Response16 {17 $email = (new Email())18 ->from(new Address('hello@mail.acme.com', 'Acme'))19 ->to('user@example.com')20 ->subject('Welcome to Acme')21 ->text('Welcome! Thanks for signing up.')22 ->html('<h1>Welcome!</h1><p>Thanks for signing up.</p>');23
24 $mailer->send($email);25
26 return new Response('Sent');27 }28}send() throws TransportExceptionInterface when the SMTP server rejects the message. If Symfony Messenger is installed, route Symfony\Component\Mailer\Messenger\SendEmailMessage to an async transport in config/packages/messenger.yaml and mail is sent by a worker instead of in the request.
WordPress
WordPress sends everything (password resets, new user emails, WooCommerce receipts) through wp_mail(), which uses PHP's mail() by default. Point it at SMTP and all of those go through Reloop.
The no-code route is an SMTP plugin such as WP Mail SMTP. The WordPress guide has the exact settings. If you prefer code, wp_mail() uses PHPMailer internally, so you can configure it with the phpmailer_init hook. Put the key in wp-config.php:
define('RELOOP_API_KEY', 'rl_your_api_key');Then add a must-use plugin:
1<?php2// wp-content/mu-plugins/reloop-smtp.php3
4add_action('phpmailer_init', function ($phpmailer) {5 $phpmailer->isSMTP();6 $phpmailer->Host = 'smtp.reloop.sh';7 $phpmailer->Port = 587;8 $phpmailer->SMTPSecure = 'tls'; // STARTTLS9 $phpmailer->SMTPAuth = true;10 $phpmailer->Username = 'reloop';11 $phpmailer->Password = RELOOP_API_KEY;12});13
14add_filter('wp_mail_from', fn () => 'hello@mail.acme.com');15add_filter('wp_mail_from_name', fn () => 'Acme');The wp_mail_from filter matters: WordPress defaults to wordpress@yourdomain.com, which must be on your verified domain to send.
Attachments
With PHPMailer, attach a file from disk or from memory:
1$mail->addAttachment('/path/to/invoice-1042.pdf', 'invoice-1042.pdf');2
3// Or from a string you generated4$mail->addStringAttachment($pdfBytes, 'invoice-1042.pdf', PHPMailer::ENCODING_BASE64, 'application/pdf');Laravel Mailables return attachments from an attachments() method, for example Attachment::fromPath(storage_path('invoices/1042.pdf')). Symfony's Email has attachFromPath() and attach().
With the SDK, pass a path that Reloop fetches when it builds the message, such as a short-lived signed URL to the file in your storage bucket:
1$reloop->mail->send([2 'from' => 'Acme Billing <billing@mail.acme.com>',3 'to' => 'user@example.com',4 'subject' => 'Your invoice #1042',5 'text' => 'Your invoice is attached.',6 'attachments' => [[7 'filename' => 'invoice-1042.pdf',8 'path' => 'https://files.acme.com/invoices/1042.pdf?signature=...',9 'content_type' => 'application/pdf',10 ]],11]);The URL must be reachable from the internet. Keep attachments small: Reloop caps them by plan (1 MB on the free plan, 5 MB on paid plans, see pricing), and large files hurt deliverability. For big files, send a download link instead.
Send in the background with a Laravel job
Sending inside a web request adds latency and fails the request when the provider is slow. Move it to a queued job and let the queue handle retries:
1<?php2
3namespace App\Jobs;4
5use Illuminate\Bus\Queueable;6use Illuminate\Contracts\Queue\ShouldQueue;7use Illuminate\Foundation\Bus\Dispatchable;8use Illuminate\Queue\InteractsWithQueue;9use Reloop\Exceptions\ReloopApiException;10use Reloop\Exceptions\ReloopValidationException;11use Reloop\Reloop;12
13class SendWelcomeEmail implements ShouldQueue14{15 use Dispatchable, InteractsWithQueue, Queueable;16
17 public int $tries = 5;18
19 public function __construct(public string $email)20 {21 }22
23 /** @return array<int, int> seconds to wait before each retry */24 public function backoff(): array25 {26 return [10, 30, 60, 120];27 }28
29 public function handle(Reloop $reloop): void30 {31 try {32 $reloop->mail->send([33 'from' => 'Acme <hello@mail.acme.com>',34 'to' => $this->email,35 'subject' => 'Welcome to Acme',36 'text' => 'Thanks for signing up.',37 ]);38 } catch (ReloopApiException $e) {39 if ($e->status === 0 || $e->status === 429 || $e->status >= 500) {40 throw $e; // the queue retries with backoff41 }42 $this->fail($e); // 4xx: do not retry43 } catch (ReloopValidationException $e) {44 $this->fail($e);45 }46 }47}SendWelcomeEmail::dispatch($user->email);Retry network errors (status 0), 429 and 5xx. Do not retry other 4xx errors: an invalid address or unverified domain fails the same way every time. Outside Laravel, Symfony Messenger and plain worker scripts follow the same rule.
Retries without duplicate emails
A request times out and your job retries. If the first attempt actually went through, the user gets two emails. The API prevents this with an Idempotency-Key header: repeat a request with the same key and Reloop returns the original result instead of sending again.
The PHP SDK does not set this header, so call the endpoint with Guzzle (already installed with the SDK):
1<?php2
3use GuzzleHttp\Client;4
5function sendReceipt(Client $http, string $orderId, string $to): array6{7 $response = $http->post('https://reloop.sh/api/mail/v1/send', [8 'headers' => [9 'x-api-key' => getenv('RELOOP_API_KEY'),10 'Idempotency-Key' => "receipt-{$orderId}",11 ],12 'json' => [13 'from' => 'Acme <orders@mail.acme.com>',14 'to' => $to,15 'subject' => "Receipt for order {$orderId}",16 'text' => 'Thanks for your order.',17 ],18 'timeout' => 30,19 ]);20
21 return json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);22}Guzzle throws ConnectException on network errors and ClientException or ServerException on 4xx and 5xx, so the same retry rules apply. In Laravel, the HTTP client does the same in a few lines:
1use Illuminate\Support\Facades\Http;2
3$response = Http::withHeaders([4 'x-api-key' => config('services.reloop.key'),5 'Idempotency-Key' => "receipt-{$order->id}",6])->timeout(30)->post('https://reloop.sh/api/mail/v1/send', [7 'from' => 'Acme <orders@mail.acme.com>',8 'to' => $order->email,9 'subject' => "Receipt for order {$order->id}",10 'text' => 'Thanks for your order.',11])->throw();Base the key on the business event (receipt-{$orderId}), not a new UUID per attempt, so retries from any worker are safe. If a retry arrives while the first request is still running, Reloop returns 409; retry that too, with the same key.
Testing without sending real email
- Laravel: call
Mail::fake()in the test, thenMail::assertSent(WelcomeMail::class)orMail::assertQueued(...). For jobs that call the API throughHttp, useHttp::fake()andHttp::assertSent(). - Symfony: set
MAILER_DSN=null://nullin.env.testto discard mail, and use the mailer assertions inKernelTestCase. - SDK unit tests:
Reloop::client()accepts a Guzzle client as its third argument, so you can pass one built on a GuzzleMockHandler(withbase_uriset tohttps://reloop.sh/) and assert on the request without network access. - Local SMTP: run Mailpit with
docker run -p 1025:1025 -p 8025:8025 axllent/mailpit, then point PHPMailer atlocalhostport1025withSMTPAuth = falseandSMTPAutoTLS = false(or setMAIL_HOST=127.0.0.1andMAIL_PORT=1025in Laravel). Openhttp://localhost:8025to see the messages. - Staging: send to test addresses so you do not hurt your sender reputation with bounces.
Production checklist
- API key in an environment variable or secrets manager, not in
config/or git - Sending domain verified with SPF, DKIM and DMARC
-
fromon your verified domain; user addresses inreply_to - Both HTML and plain-text bodies, UTF-8 charset
- No calls to
mail()anywhere, including old plugins - One shared SDK client, bound as a singleton
- Sending in a queue worker, not the request
- Retries only on network errors,
429and5xx - Idempotency keys on anything that retries
- Webhooks for bounces and complaints
- Disposable addresses blocked at signup (how)
FAQ
With PHPMailer, call isHTML(true), put the HTML in Body and the plain-text version in AltBody. With the Reloop SDK, pass html and text keys in the send array. In Laravel, give the Mailable both a view and a text view.
mail() passes the message to the local sendmail binary without authentication or DKIM signing, so it often lands in spam or is rejected. It only tells you whether sendmail accepted the message, not whether it was delivered. Use PHPMailer over SMTP or an email API instead.
STARTTLS connects in plain text and upgrades to TLS, which is what port 587 expects. SMTPS starts TLS immediately, which is what port 465 expects. Using the wrong one for the port makes the connection hang or fail. Reloop uses STARTTLS on every port, so set SMTPSecure to the STARTTLS constant.
Usually the sending domain is not authenticated, the mail comes from mail() on a shared server, or the From domain does not match the domain that signed the message. Send through a provider from your own verified domain with SPF, DKIM and DMARC, and always include a plain-text body.
Yes. Set the SMTP values shown above in Laravel's .env file, or point WordPress at Reloop with an SMTP plugin or a small must-use plugin, and every email the framework sends goes through Reloop with no other code changes.
Ship your first email with Reloop
in minutes.
Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.


