PHP SDK
Send email with CodeIgniter
Use the Parcel Wing PHP SDK from CodeIgniter controllers while keeping your API key on the server.
Install the SDK
Install the official PHP SDK with Composer.
Terminal
composer require parcelwing/parcelwing-php
Configure CodeIgniter
Store the Parcel Wing API key and default sender in your environment. Do not expose either value to browser-side code.
.env
PARCELWING_API_KEY=pw_live_...PARCELWING_FROM_EMAIL="Acme <[email protected]>"
Create a mail library
A small library centralizes template aliases, sender addresses, and Parcel Wing exception handling.
app/Libraries/ParcelWingMail.php
<?phpnamespace App\Libraries;use ParcelWing\ParcelWing;use ParcelWing\Exceptions\ParcelWingException;class ParcelWingMail{public function __construct(private ?ParcelWing $client = null){$this->client = $client ?: new ParcelWing(getenv('PARCELWING_API_KEY'));}/** @throws ParcelWingException */public function sendWelcome(string $email, ?string $firstName = null): array{$messages = $this->client->emails->send(['from' => getenv('PARCELWING_FROM_EMAIL'),'to' => $email,'template_alias' => 'welcome','template_params' => ['first_name' => $firstName ?: 'friend',],]);return $messages[0];}}
Send from a controller
Validate the incoming request, send the email, and return the queued message ID.
app/Controllers/WelcomeEmailController.php
<?phpnamespace App\Controllers;use App\Libraries\ParcelWingMail;use CodeIgniter\HTTP\ResponseInterface;use ParcelWing\Exceptions\ParcelWingException;class WelcomeEmailController extends BaseController{public function create(): ResponseInterface{$rules = ['email' => 'required|valid_email','first_name' => 'permit_empty|string',];if (! $this->validate($rules)) {return $this->response->setStatusCode(422)->setJSON(['errors' => $this->validator->getErrors(),]);}$payload = $this->request->getJSON(true) ?: $this->request->getPost();try {$message = (new ParcelWingMail())->sendWelcome($payload['email'],$payload['first_name'] ?? null,);return $this->response->setJSON(['id' => $message['id']]);} catch (ParcelWingException $error) {log_message('error', 'Parcel Wing send failed: ' . $error->getMessage());return $this->response->setStatusCode($error->status ?: 500)->setJSON(['code' => $error->errorCode,]);}}}
app/Config/Routes.php
$routes->post('send-welcome', 'WelcomeEmailController::create');