定制 smtp2go-oss/smtp2go-php 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

smtp2go-oss/smtp2go-php

Composer 安装命令:

composer require smtp2go-oss/smtp2go-php

包简介

A library for sending email through the SMTP2GO Api

README 文档

README

This library provides a simple way to send email via the SMTP2GO API and also access other endpoints in the API in a standard way.

Requirements

  • PHP >= 7.4
  • Guzzle ^7.0 (installed automatically via Composer)

Installation

composer require smtp2go-oss/smtp2go-php

You can obtain an API key from app.smtp2go.com/settings/apikeys.

Examples

Sending an Email

use SMTP2GO\ApiClient;
use SMTP2GO\Service\Mail\Send as MailSend;
use SMTP2GO\Types\Mail\Address;
use SMTP2GO\Collections\Mail\AddressCollection;
use SMTP2GO\Collections\Mail\AttachmentCollection;
use SMTP2GO\Types\Mail\FileAttachment;
use SMTP2GO\Types\Mail\InlineAttachment;
use SMTP2GO\Types\Mail\CustomHeader;

$message = <<<EOF

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<h1>This should contain an image of a cat. It should appear as an inline attachment.</h1>
<img src="cid:a-cat-picture" alt="a cat"/>
</body>
</html>
EOF;

$sendService = new MailSend(
    new Address('sender@email.test', 'Sender Name'),
    new AddressCollection([
        new Address('recipient@email.test', 'Recipient Name'),
        new Address('recipient2@email.test', 'Recipient Name 2'),
    ]),
    'Test Email',
   $message,
);

$sendService->addAddress('cc', new Address('cc@email.test'));
$sendService->addAddress('bcc', new Address('bcc@email.test'));

$sendService->setAttachments(new AttachmentCollection([ new FileAttachment('attachment-data','file1.txt'), new FileAttachment('another-attachment-data','file2.txt')]));

$inline = new InlineAttachment('a-cat-picture', file_get_contents('attachments/cat.jpg'), 'image/jpeg');

$sendService->addAttachment($inline);

$sendService->addCustomHeader(new CustomHeader('Reply-To', 'replyto@email.test'));

$apiClient = new ApiClient('api-YOURAPIKEY');

#set a custom region
$apiClient->setApiRegion('us');

#set the client to retry using a different server ip if possible
$apiClient->setMaxSendAttempts(5);

#set the number of seconds to increase the request timeout with each attempt
$apiClient->setTimeoutIncrement(5);

$success = $apiClient->consume($sendService);

$responseBody = $apiClient->getResponseBody();

Handling the Response

consume() returns true if the API responded with HTTP 200, false otherwise. Use the response methods to inspect the result or diagnose failures:

$success = $apiClient->consume($sendService);

if ($success) {
    $body = $apiClient->getResponseBody(); // stdClass
    echo $body->data->succeeded; // number of messages queued
} else {
    $body = $apiClient->getResponseBody();
    echo $body->data->error;      // human-readable error message
    echo $body->data->error_code; // machine-readable error code

    // If an exception was thrown (e.g. connection failure):
    echo $apiClient->getLastRequest();          // the outgoing request as a string
    echo $apiClient->getLastResponseStatusCode(); // HTTP status code, or null
}

To get the raw response headers:

$headers = $apiClient->getResponseHeaders(); // array

Scheduling an Email

Pass a Unix timestamp up to 3 days in the future to scheduleAt():

$sendService->scheduleAt(strtotime('+2 hours'));
$apiClient->consume($sendService);

Retry / Failover

When setMaxSendAttempts() is greater than 1, the client will automatically resolve alternative IP addresses for api.smtp2go.com and retry failed requests against them, increasing the timeout by setTimeoutIncrement() seconds on each attempt. Useful for high-reliability sending.

$apiClient->setMaxSendAttempts(5);   // try up to 5 different IPs
$apiClient->setTimeoutIncrement(5);  // add 5 seconds to timeout per attempt

After a failed send you can inspect what happened:

foreach ($apiClient->getFailedAttemptInfo() as $attempt) {
    echo $attempt['ip'];    // IP that was tried
    echo $attempt['error']; // exception message
}
echo $apiClient->getFailedAttempts(); // total number of failed attempts

Attachments

FileAttachment - attach a file by passing its raw content and a filename. The MIME type is detected automatically from the filename extension:

use SMTP2GO\Types\Mail\FileAttachment;
use SMTP2GO\Collections\Mail\AttachmentCollection;

$sendService->setAttachments(new AttachmentCollection([
    new FileAttachment(file_get_contents('/path/to/report.pdf'), 'report.pdf'),
]));

InlineAttachment - embed an image directly in the HTML body using a content ID:

use SMTP2GO\Types\Mail\InlineAttachment;

// Reference in your HTML as: <img src="cid:my-image">
$inline = new InlineAttachment('my-image', file_get_contents('/path/to/image.jpg'), 'image/jpeg');
$sendService->addAttachment($inline);

Custom Headers

use SMTP2GO\Types\Mail\CustomHeader;

$sendService->addCustomHeader(new CustomHeader('Reply-To', 'replyto@email.test'));
$sendService->addCustomHeader(new CustomHeader('X-Mailer', 'MyApp'));

Sending email using a template

https://app-us.smtp2go.com/settings/templates/

This sample code is for the example template "User Welcome"

use SMTP2GO\ApiClient;
use SMTP2GO\Types\Mail\Address;
use SMTP2GO\Service\Mail\Send as MailSend;
use SMTP2GO\Collections\Mail\AddressCollection;

$client = new ApiClient('api-YOURAPIKEY');
$sendService = new MailSend(
    new Address('sender@site.test', 'Sender Name'),
    new AddressCollection([
        new Address('recipient@example.test', 'Bob Recipient'),
    ]),
    '', //subject is empty as this is defined in the template
    '', //body is empty as this is generated from the template
);
$sendService->setTemplateId(6040276);
$sendService->setTemplateData([
    "username" => "Steve",
    "product_name" => "Widgets",
    "action_url" => "https://website.localhost",
    "login_url" => "https://website.localhost/login",
    "guide_url" => "https://website.localhost/guide",
    "support_email" => "support@website.localhost",
    "sender_name" => "Bob Widgets"
]);

$res = $client->consume($sendService);

Consuming an endpoint in the API using the Service class

use SMTP2GO\ApiClient;
use SMTP2GO\Service\Service;

$client = new ApiClient('api-YOURAPIKEY');

$success = $client->consume((new Service('domain/verify', ['domain' => 'mydomain.tld'])));

License

The package is available as open source under the terms of the MIT License.

smtp2go-oss/smtp2go-php 适用场景与选型建议

smtp2go-oss/smtp2go-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 30.24k 次下载、GitHub Stars 达 13, 最近一次更新时间为 2021 年 06 月 08 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 smtp2go-oss/smtp2go-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 smtp2go-oss/smtp2go-php 我们能提供哪些服务?
定制开发 / 二次开发

基于 smtp2go-oss/smtp2go-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 30.24k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 13
  • 点击次数: 19
  • 依赖项目数: 3
  • 推荐数: 0

GitHub 信息

  • Stars: 13
  • Watchers: 4
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-06-08