railsware/mailtrap-php 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

railsware/mailtrap-php

Composer 安装命令:

composer require railsware/mailtrap-php

包简介

The Mailtrap SDK provides methods for all API functions.

README 文档

README

GitHub Actions GitHub Actions

PHP version support Latest Version on Packagist Total Downloads

Prerequisites

To get the most of this official Mailtrap.io PHP SDK:

Installation

You can install the package via composer

The Mailtrap API Client is not hard coupled to Guzzle, React, Zend, Symfony HTTP or any other library that sends HTTP messages. Instead, it uses the PSR-18 client abstraction.

This will give you the flexibility to choose what HTTP client you want to use.

If you just want to get started quickly you should run one of the following command (depends on which HTTP client you want to use):

# With symfony http client (recommend)
composer require railsware/mailtrap-php symfony/http-client nyholm/psr7

# Or with guzzle http client
composer require railsware/mailtrap-php guzzlehttp/guzzle php-http/guzzle7-adapter

Framework integration

If you use a framework, install a bridge package for seamless configuration:

These provide service registration and allow you to inject the client where needed with minimal manual bootstrapping.

Usage

You should use Composer autoloader in your application to automatically load your dependencies.

Minimal usage (Transactional sending)

The quickest way to send a single transactional email with only the required parameters:

<?php

use Mailtrap\Helper\ResponseHelper;
use Mailtrap\MailtrapClient;
use Mailtrap\Mime\MailtrapEmail;
use Symfony\Component\Mime\Address;

require __DIR__ . '/vendor/autoload.php';

$mailtrap = MailtrapClient::initSendingEmails(
    apiKey: getenv('MAILTRAP_API_KEY') // your API key here https://mailtrap.io/api-tokens
);

$email = (new MailtrapEmail())
    ->from(new Address('sender@example.com'))
    ->to(new Address('recipient@example.com'))
    ->subject('Hello from Mailtrap PHP')
    ->text('Plain text body');

$response = $mailtrap->send($email);

// Access response body as array (helper optional)
var_dump(ResponseHelper::toArray($response));

Sandbox vs Production (easy switching)

Mailtrap lets you test safely in the Email Sandbox and then switch to Production (Sending) with one flag.

Example .env variables (or export in shell):

MAILTRAP_API_KEY=your_api_token # https://mailtrap.io/api-tokens
MAILTRAP_USE_SANDBOX=true       # true/false toggle
MAILTRAP_INBOX_ID=123456        # Only needed for sandbox

Bootstrap logic:

<?php

use Mailtrap\Helper\ResponseHelper;
use Mailtrap\MailtrapClient;
use Mailtrap\Mime\MailtrapEmail;
use Symfony\Component\Mime\Address;

require __DIR__ . '/vendor/autoload.php';

$apiKey    = getenv('MAILTRAP_API_KEY');
$isSandbox = filter_var(getenv('MAILTRAP_USE_SANDBOX'), FILTER_VALIDATE_BOOL);
$inboxId   = $isSandbox ? getenv('MAILTRAP_INBOX_ID') : null; // required only for sandbox

$client = MailtrapClient::initSendingEmails(
    apiKey: $apiKey,
    isSandbox: $isSandbox,
    inboxId: $inboxId // null is ignored for production
);

$email = (new MailtrapEmail())
    ->from(new Address($isSandbox ? 'sandbox@example.com' : 'no-reply@your-domain.com'))
    ->to(new Address('recipient@example.com'))
    ->subject($isSandbox ? '[SANDBOX] Demo email' : 'Welcome onboard')
    ->text('This is a minimal body for demonstration purposes.');

$response = $client->send($email);

// Access response body as array (helper optional)
var_dump(ResponseHelper::toArray($response));

Bulk stream example (optional) differs only by setting isBulk: true:

$bulkClient = MailtrapClient::initSendingEmails(apiKey: $apiKey, isBulk: true);

Recommendations:

  • Toggle sandbox with MAILTRAP_USE_SANDBOX.
  • Use separate API tokens for Production and Sandbox.
  • Keep initialisation in a single factory object/service so that switching is centralised.

Full-featured usage example

<?php

use Mailtrap\Helper\ResponseHelper;
use Mailtrap\MailtrapClient;
use Mailtrap\Mime\MailtrapEmail;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Header\UnstructuredHeader;

require __DIR__ . '/vendor/autoload.php';

// Init Mailtrap client depending on your needs
$mailtrap = MailtrapClient::initSendingEmails(
    apiKey: getenv('MAILTRAP_API_KEY'), # your API token
    isBulk: false,                      # set to true for bulk email sending (false by default)
    isSandbox: false,                   # set to true for sandbox mode       (false by default)
    inboxId: null                       # optional, only for sandbox mode    (false by default)
);

$email = (new MailtrapEmail())
    ->from(new Address('example@your-domain-here.com', 'Mailtrap Test'))
    ->replyTo(new Address('reply@your-domain-here.com'))
    ->to(new Address('email@example.com', 'Jon'))
    ->priority(Email::PRIORITY_HIGH)
    ->cc('mailtrapqa@example.com')
    ->addCc('staging@example.com')
    ->bcc('mailtrapdev@example.com')
    ->subject('Best practices of building HTML emails')
    ->text('Hey! Learn the best practices of building HTML emails and play with ready-to-go templates. Mailtrap\'s Guide on How to Build HTML Email is live on our blog')
    ->html(
        '<html>
        <body>
        <p><br>Hey</br>
        Learn the best practices of building HTML emails and play with ready-to-go templates.</p>
        <p><a href="https://mailtrap.io/blog/build-html-email/">Mailtrap\'s Guide on How to Build HTML Email</a> is live on our blog</p>
        <img src="cid:logo">
        </body>
    </html>'
    )
    ->embed(fopen('https://mailtrap.io/wp-content/uploads/2021/04/mailtrap-new-logo.svg', 'r'), 'logo', 'image/svg+xml')
    ->category('Integration Test')
    ->customVariables([
        'user_id' => '45982',
        'batch_id' => 'PSJ-12'
    ])
;

// Custom email headers (optional)
$email->getHeaders()
    ->addTextHeader('X-Message-Source', 'domain.com')
    ->add(new UnstructuredHeader('X-Mailer', 'Mailtrap PHP Client')) // the same as addTextHeader
;

try {
    $response = $mailtrap->send($email);

    var_dump(ResponseHelper::toArray($response)); // body (array)
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}


// OR Template email sending

$email = (new MailtrapEmail())
    ->from(new Address('example@your-domain-here.com', 'Mailtrap Test'))
    ->replyTo(new Address('reply@your-domain-here.com'))
    ->to(new Address('example@gmail.com', 'Jon'))
    ->templateUuid('bfa432fd-0000-0000-0000-8493da283a69')
    ->templateVariables([
        'user_name' => 'Jon Bush',
        'next_step_link' => 'https://mailtrap.io/',
        'get_started_link' => 'https://mailtrap.io/',
        'onboarding_video_link' => 'some_video_link',
        'company' => [
            'name' => 'Best Company',
            'address' => 'Its Address',
        ],
        'products' => [
            [
                'name' => 'Product 1',
                'price' => 100,
            ],
            [
                'name' => 'Product 2',
                'price' => 200,
            ],
        ],
        'isBool' => true,
        'int' => 123
    ])
;

try {
    $response = $mailtrap->send($email);

    var_dump(ResponseHelper::toArray($response)); // body (array)
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

Supported functionality & Examples

Email API:

Email Sandbox (Testing):

Contact management:

General API:

Framework-specific (quick starts):

See the full indexed list at examples/README.md.

Webhooks:

Contributing

Bug reports and pull requests are welcome on GitHub. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

License

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

Code of Conduct

Everyone interacting in the Mailtrap project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

railsware/mailtrap-php 适用场景与选型建议

railsware/mailtrap-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 944.63k 次下载、GitHub Stars 达 60, 最近一次更新时间为 2023 年 03 月 29 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「mail」 「symfony」 「php」 「plugin」 「email」 「sdk」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

  • Stars: 60
  • Watchers: 14
  • Forks: 17
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-03-29