PHP code example of elasticemail / elasticemail-php
1. Go to this page and download the library: Download elasticemail/elasticemail-php library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
elasticemail / elasticemail-php example snippets
ElasticEmail\Api\EmailsApi;
use ElasticEmail\ApiException;
use ElasticEmail\Configuration;
use ElasticEmail\Model;
$config = Configuration::getDefaultConfiguration()
->setApiKey('X-ElasticEmail-ApiKey', getenv('ELASTICEMAIL_API_KEY'));
$emails = new EmailsApi(new GuzzleHttp\Client(), $config);
$message = new Model\EmailTransactionalMessageData([
'recipients' => new Model\TransactionalRecipient([
'to' => ['[email protected]'],
]),
'content' => new Model\EmailContent([
'from' => 'My App <[email protected]>',
'subject' => 'Welcome aboard!',
'body' => [
new Model\BodyPart([
'content_type' => Model\BodyContentType::HTML,
'content' => '<h1>Hello!</h1><p>Thanks for signing up.</p>',
]),
new Model\BodyPart([
'content_type' => Model\BodyContentType::PLAIN_TEXT,
'content' => 'Hello! Thanks for signing up.',
]),
],
]),
]);
try {
$result = $emails->emailsTransactionalPost($message);
echo "Sent. TransactionID: {$result->getTransactionId()}, MessageID: {$result->getMessageId()}", PHP_EOL;
} catch (ApiException $e) {
echo "Elastic Email API error {$e->getCode()}: {$e->getMessage()}", PHP_EOL;
}
// One key per logical send (a UUID v4); reuse it only to retry that same send.
$bytes = random_bytes(16);
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40);
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80);
$idempotencyKey = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
for ($attempt = 1; ; $attempt++) {
try {
$result = $emails->emailsTransactionalPost($message, $idempotencyKey);
break;
} catch (ApiException $e) {
// Retry network errors (code 0), 409 and 5xx with the same key and the same $message.
$retryable = $e->getCode() === 0 || $e->getCode() === 409 || $e->getCode() >= 500;
if (!$retryable || $attempt === 3) {
throw $e;
}
sleep((int) ($e->getResponseHeaders()['Retry-After'][0] ?? 2));
}
}