PHP SDK
Send email with Yii
Use the Parcel Wing PHP SDK from a Yii application component and call it from controllers, jobs, or services.
Install the SDK
Install the official PHP SDK with Composer.
Terminal
composer require parcelwing/parcelwing-php
Yii version note
The Yii ecosystem is moving forward with Yii 3, while many production applications still use the familiar Yii 2 controller and component layout. The example below uses that component pattern because it maps cleanly to existing Yii apps. In Yii 3-style applications, register the same ParcelWing client in your container and inject it into your action or service instead.
Configure Yii
Store the Parcel Wing API key and default sender in environment variables, then register a mail component in your Yii config.
.env
PARCELWING_API_KEY=pw_live_...PARCELWING_FROM_EMAIL="Acme <[email protected]>"
config/web.php
'components' => ['parcelWingMail' => ['class' => app\components\ParcelWingMail::class,'apiKey' => getenv('PARCELWING_API_KEY'),'fromEmail' => getenv('PARCELWING_FROM_EMAIL'),],],
Create a mail component
Keep the Parcel Wing client and template-specific send logic inside a reusable application component.
components/ParcelWingMail.php
<?phpnamespace app\components;use ParcelWing\ParcelWing;use ParcelWing\Exceptions\ParcelWingException;use yii\base\Component;class ParcelWingMail extends Component{public string $apiKey;public string $fromEmail;private ParcelWing $client;public function init(): void{parent::init();$this->client = new ParcelWing($this->apiKey);}/** @throws ParcelWingException */public function sendWelcome(string $email, ?string $firstName = null): array{$messages = $this->client->emails->send(['from' => $this->fromEmail,'to' => $email,'template_alias' => 'welcome','template_params' => ['first_name' => $firstName ?: 'friend',],]);return $messages[0];}}
Send from a controller
Call the component from a REST controller, then return the queued message ID to your client.
controllers/WelcomeEmailController.php
<?phpnamespace app\controllers;use ParcelWing\Exceptions\ParcelWingException;use Yii;use yii\rest\Controller;use yii\web\BadRequestHttpException;use yii\web\Response;use yii\web\ServerErrorHttpException;class WelcomeEmailController extends Controller{public function actionCreate(): array{Yii::$app->response->format = Response::FORMAT_JSON;$payload = Yii::$app->request->bodyParams;if (empty($payload['email'])) {throw new BadRequestHttpException('email is required');}try {$message = Yii::$app->parcelWingMail->sendWelcome($payload['email'],$payload['first_name'] ?? null,);return ['id' => $message['id']];} catch (ParcelWingException $error) {Yii::error(['message' => $error->getMessage(),'status' => $error->status,'code' => $error->errorCode,], 'parcelwing');throw new ServerErrorHttpException('Email could not be queued.');}}}
config/web.php
'urlManager' => ['enablePrettyUrl' => true,'showScriptName' => false,'rules' => ['POST send-welcome' => 'welcome-email/create',],],