freshmail/php-api-client

FreshMail API PHP 客户端

1.6.0 2024-01-29 12:23 UTC

README

Freshmail API V3 PHP 客户端

官方 API V3 文档

此 API V3 客户端仅涵盖通过 FreshMail 应用发送事务性邮件。如果您想使用 API 的其他功能,请使用 API V2 客户端

要求

  • PHP7.2 及以上

安装

更新 composer.json 并运行 composer update

{
    "require": {
        "freshmail/php-api-client": "^1.0"
    }
}

或者执行

composer require freshmail/php-api-client

使用方法

发送事务性邮件

use \FreshMail\Api\Client\Service\Messaging\Mail;
use \FreshMail\Api\Client\Messaging\Mail\MailBag;

$token = 'MY_APP_TOKEN';
$mailService = new Mail($token);

$mail = new MailBag();
$mail->setFrom('from@address.com', 'Office');
$mail->setSubject('That\'s my awesome first mail!');
$mail->setHtml('<html><body><strong>Look!</strong> its working!</body></html>');
$mail->addRecipientTo('recipient email address');

$response = $mailService->send($mail);

处理响应对象

if ($response->isSuccess()) {
    $responseData = $response->getData();    
}

处理原始 PSR-7 ResponseInterface

$response->getPsr7Response();

发送个性化邮件

use \FreshMail\Api\Client\Service\Messaging\Mail;
use \FreshMail\Api\Client\Messaging\Mail\MailBag;

$token = 'MY_APP_TOKEN';
$mailService = new Mail($token);

$mail = new MailBag();
$mail->setFrom('from@address.com', 'Office');
$mail->setSubject('Hello $$first_name$$! I\'v got promotion code for You!');
$mail->setHtml('<html><body>Your code is <strong>$$code$$</strong></body></html>');
$mail->addRecipientTo('recipient email address', [
    'first_name' => 'Joshua',
    'code' => 'CODE1234'
]);

$response = $mailService->send($mail);

发送多封邮件

您可以通过一个请求发送多封邮件。这种方式比逐封发送邮件要快得多。在一个请求中,您可以发送多达 100 封邮件。

use \FreshMail\Api\Client\Service\Messaging\Mail;
use \FreshMail\Api\Client\Messaging\Mail\MailBag;

$token = 'MY_APP_TOKEN';
$mailService = new Mail($token);

$mail = new MailBag();
$mail->setFrom('from@address.com', 'Office');
$mail->setSubject('Hello $$first_name$$! I\'v got promotion code for You!');
$mail->setHtml('<html><body>Your code is <strong>$$code$$</strong></body></html>');

//first recipient
$mail->addRecipientTo('recipient email address', [
    'first_name' => 'Joshua',
    'code' => '10percentDISCOUNT'
]);

//second recipient
$mail->addRecipientTo('second recipient email address', [
    'first_name' => 'Donald',
    'code' => '25percentDISCOUNT'
]);

//third recipient
$mail->addRecipientTo('third recipient email address', [
    'first_name' => 'Abbie',
    'code' => 'FREEshippingDISCOUNT'
]);

$response = $mailService->send($mail);

从模板发送邮件

您可以使用 FreshMail 模板机制来优化对 API 的请求。此外,您还可以在 FreshMail 中修改邮件内容,而不需要修改应用程序的代码。

use \FreshMail\Api\Client\Service\Messaging\Mail;
use \FreshMail\Api\Client\Messaging\Mail\MailBag;

$token = 'MY_APP_TOKEN';
$mailService = new Mail($token);

$mail = new MailBag();
$mail->setFrom('from@address.com', 'Support');
$mail->setSubject('Hello, that\'s my email genereted by template!');
$mail->setTemplateHash('TEMPLATE_HASH');
$mail->addRecipientTo('recipient email address');

$response = $mailService->send($mail);

发送带附件的邮件

您可以发送带附件的邮件。您可以上传最多 10 个文件。邮件中所有附件的总大小不能超过 10Mb。

use \FreshMail\Api\Client\Service\Messaging\Mail;
use \FreshMail\Api\Client\Messaging\Mail\Base64Attachment;
use \FreshMail\Api\Client\Messaging\Mail\LocalFileAttachment;
use \FreshMail\Api\Client\Messaging\Mail\MailBag;

$token = 'MY_APP_TOKEN';
$mailService = new Mail($token);

//attachment from hard drive
$localFileAttachment = new LocalFileAttachment(
    '/my/local/path/file.extension',
    'optional file name'
);

//attachment from base64 
$base64Attachment = new Base64Attachment(
    'example.txt',
    base64_encode('example content')
);

$mail = new MailBag();
$mail->setFrom('from@address.com', 'Support');
$mail->setSubject('Hello, thats mail with attachments!!');
$mail->setHtml('<html><body><strong>Attachments</strong> in mail</body></html>');
$mail->addRecipientTo('recipient email address');

$mail->addAttachment($localFileAttachment); 
$mail->addAttachment($base64Attachment);

$response = $mailService->send($mail);

错误处理

API 会抛出异常,以处理请求过程中发生的错误以及在发送请求之前发生的错误。

  • 如果由于错误的 API 使用而未将请求发送到服务器,将抛出 FreshMail\Api\Client\Exception\ApiUsageException。此类异常表示,例如,向某些方法传递了错误的参数或在事务性邮件中同时传递内容和模板,这意味着请求不会被接受,因此 API 不会进行任何请求。
  • 如果请求已发送,但发生了某些网络问题(DNS 错误、连接超时、防火墙阻止请求),则抛出 FreshMail\Api\Client\Exception\RequestException
  • 如果请求已发送,收到响应,但服务器发生了一些错误(500 级 HTTP 状态码),则抛出 FreshMail\Api\Client\Exception\ServerException
  • 如果请求已发送,收到响应,但发生了一些客户端错误(400 级 HTTP 状态码),则抛出 FreshMail\Api\Client\Exception\ClientError。此错误消息具有 getRequestgetResponse 方法,可以接收原始请求和响应对象(由 PSR-7 的 Psr\Http\Message\RequestInterfacePsr\Http\Message\ResponseInterface 实现)。
use FreshMail\Api\Client\Exception\ClientError;

try {
    $response = $mailService->send($mail);
} catch (ClientException $exception) {
    echo $exception->getRequest()->getBody();
    echo $exception->getResponse()->getBody();
}

FreshMail\Api\Client\Exception\RequestExceptionFreshMail\Api\Client\Exception\ClientExceptionFreshMail\Api\Client\Exception\ServerException 都继承自 FreshMail\Api\Client\Exception\TransferExceptionFreshMail\Api\Client\Exception\TransferExceptionFreshMail\Api\Client\Exception\ApiUsageException 都继承自 FreshMail\Api\Client\Exception\GeneralApiException。所有异常都具有 hasRequesthasResponse 方法。

use FreshMail\Api\Client\Exception\GeneralApiException;

try {
    $response = $mailService->send($mail);
} catch (GeneralApiException $exception) {
    $error = $exception->getMessage();
    if ($exception->hasRequest()) {
        $request = (string) $exception->getRequest()->getBody();
    }
    
    if ($exception->hasResponse()) {
        $response = (string) $exception->getResponse()->getBody();
    }
}

代理设置

如果您需要配置代理,可以使用自定义的 GuzzleHttp\Client 对象。

use \FreshMail\Api\Client\Service\Messaging\Mail;

$client = new \GuzzleHttp\Client(
    [
        'proxy' => 'my proxy url'
    ]
);

$token = 'MY_APP_TOKEN';
$mailService = new Mail($token);
$mailService->setGuzzleHttpClient($client);

日志记录和调试

如果您需要记录或调试您的请求,您可以使用以下两个功能。

PSR-3 日志记录器接口

您可以使用任何实现了 PSR-3 的库 Psr\Log\LoggerInterface,以下是一个使用 Monolog 的示例。

use \FreshMail\Api\Client\Service\Messaging\Mail;

$logger = new \Monolog\Logger('myCustomLogger');
$logger->pushHandler(new \Monolog\Handler\StreamHandler('php://stderr', \Monolog\Logger::DEBUG));

$token = 'MY_APP_TOKEN';
$mailService = new Mail($token);
$mailService->setLogger($logger);

通过 GuzzleHttp 客户端进行日志记录

要使用请求API,请使用GuzzleHttp\Client对象。如果您想,您可以根据需要对其进行配置,特别是可以在客户端中启用日志记录。

use \FreshMail\Api\Client\Service\Messaging\Mail;

$stack = \GuzzleHttp\HandlerStack::create();
$stack->push(
    \GuzzleHttp\Middleware::log(
        new \Monolog\Logger('Logger'),
        new \GuzzleHttp\MessageFormatter('{req_body} - {res_body}')
    )
);

$client = new \GuzzleHttp\Client(
    [
        'handler' => $stack,
    ]
);

$token = 'MY_APP_TOKEN';
$mailService = new Mail($token);
$mailService->setGuzzleHttpClient($client);