mailslurp/mailslurp-client-php

MailSlurp 是一个API,可以用于从动态分配的电子邮件地址发送和接收电子邮件。它专为开发人员和QA团队设计,用于测试应用程序、处理传入的电子邮件、发送模板化通知、附件等。## 资源 - [主页](https://www.mailslurp.com) - 获取一个

15.19.22 2024-06-03 06:06 UTC

This package is auto-updated.

Last update: 2024-09-03 06:37:49 UTC


README

使用PHP创建和管理电子邮件地址和电话号码。在代码和测试中发送和接收电子邮件、附件和短信。以下是一个快速示例

// configure mailslurp/mailslurp-client-php library
$config = MailSlurp\Configuration::getDefaultConfiguration()
    ->setApiKey('x-api-key', getenv("API_KEY"));
$inboxController = new MailSlurp\Apis\InboxControllerApi(null, $config);
// create an inbox
$inbox = $inboxController->createInboxWithDefaults();
// send an email
$sendOptions = new MailSlurp\Models\SendEmailOptions();
$sendOptions->setTo([$inbox->getEmailAddress()]);
$sendOptions->setSubject("Test");
$sendOptions->setBody("Hello");
$inboxController->sendEmail($inbox->getId(), $sendOptions);
// receive the email
$waitForController = new MailSlurp\Apis\WaitForControllerApi(null, $config);
$email = $waitForController->waitForLatestEmail($inbox->getId(), 120000, true);
$this->assertNotNull($email->getBody());

视频教程

PHP mailslurp tutorial

快速链接

示例

开始使用

MailSlurp是一个电子邮件API,它允许您按需创建电子邮件地址,然后在代码和测试中发送和接收电子邮件。**不需要邮件服务器**。

本节描述了如何使用PHP客户端启动。要使用其他语言或REST API,请参阅开发者页面

查看示例页面以获取代码示例和与常见框架一起使用

查看方法文档,了解所有函数的列表

获取API密钥

您需要一个免费的MailSlurp账户才能使用此服务。首先注册免费账户

注册后,请登录仪表板。找到您的API密钥并复制代码。您将需要它来配置PHP中的MailSlurp客户端。

find-api-key

MailSlurp仪表板复制您的API密钥。

PHP设置

客户端已在PHP 7上进行了测试,需要安装以下非默认PHP扩展

php-ext-curl
php-xml
php-mbstring

通常,这些扩展包含在大多数PHP安装中。在Linux上,也可以按如下方式安装

sudo apt-get install php-ext-curl php-mbstring php-xml

添加PHP库

有几种方法可以安装MailSlurp。

a) Composer依赖项

如果您使用composer包管理器,则可以运行

composer require mailslurp/mailslurp-client-php

或将它添加到您的composer.json文件中

{
  "repositories": [
    {
      "type": "vcs",
      "url": "https://github.com/mailslurp/mailslurp-client-php.git"
    }
  ],
  "require": {
    "mailslurp/mailslurp-client-php": "*@dev"
  }
}

然后使用composer自动加载约定包含库

<?php
// assuming your file is in root directory and a vendor folder exists next to it
require_once(__DIR__ . '/vendor/autoload.php');

b) 手动安装

或者,您可以直接下载PHP库并将其包含在项目的根目录中。

php-email-library-github

MailSlurp仪表板下载MailSlurp PHP电子邮件库。

然后包含文件以在代码中访问MailSlurp

<?php
require_once('/path/to/MailSlurpClient/vendor/autoload.php');

创建API实例

要调用MailSlurp API,您必须创建要访问的控制器的一个实例。每个实例都必须配置API密钥。有关所有控制器和方法的列表,请参阅方法文档

配置API密钥

private function getConfig()
{
    // create a mailslurp configuration with API_KEY environment variable
    // get your own free API KEY at https://app.mailslurp.com/sign-up/
    return MailSlurp\Configuration::getDefaultConfiguration()
        ->setApiKey('x-api-key', getenv("API_KEY"));
}

创建控制器

$inboxController = new MailSlurp\Apis\InboxControllerApi(null, $this->getConfig());

基本用法

一个常见的用例是创建一个新的电子邮件地址,向其发送电子邮件,然后接收内容

创建电子邮件地址

要创建电子邮件地址,请使用收件箱控制器创建新的收件箱。收件箱具有真实电子邮件地址,可以发送和接收电子邮件以及附件。

$options = new \MailSlurp\Models\CreateInboxDto();
$options->setName("Test inbox");
$options->setPrefix("test");
$inbox = $inboxController->createInboxWithOptions($options);

发送电子邮件

以下是一个发送电子邮件的简单示例

$send_options = new MailSlurp\Models\SendEmailOptions();
$send_options->setTo([$inbox->getEmailAddress()]);
$send_options->setSubject("Test");
$send_options->setBody("Confirmation code = abc123");
$inbox_controller->sendEmail($inbox_2->getId(), $send_options);

阅读电子邮件

您可以使用WaitFor控制器方法等待预期电子邮件到达收件箱

$wait_for_controller = new MailSlurp\Apis\WaitForControllerApi(null, $this->getConfig());

然后可以这样调用它

$timeout_ms = 30000;
$unread_only = true;
$email = $wait_for_controller->waitForLatestEmail($inbox->getId(), $timeout_ms, $unread_only);

获取电子邮件

您可以使用收件箱控制器从收件箱中获取电子邮件

您还可以以分页形式获取

获取电子邮件

使用电子邮件控制器直接通过ID获取电子邮件

s
        $emails = $inbox_controller->getEmails($inbox->getId());
        

SMTP访问(PHPMailer、mail函数等)

SMTP收件箱通过getImapSmtpAccess函数提供IMAP和SMTP访问凭据。使用这些凭据配置PHPMailer、PearMailer或其他SMTP发送客户端。首先创建一个SMTP_INBOX

$options = new \MailSlurp\Models\CreateInboxDto();
$options->setInboxType("SMTP_INBOX");
$inbox_smtp = $inboxController->createInboxWithOptions($options);

然后使用访问设置来配置PHPMailer

$access_details = $inboxController->getImapSmtpAccess($inbox_smtp->getId());
$mail = new PHPMailer\PHPMailer\PHPMailer(true);
// set mail server settings using the inbox access details
$mail->isSMTP();
$mail->Host       = $access_details->getSecureSmtpServerHost();
$mail->SMTPAuth   = true;
$mail->Username   = $access_details->getSecureSmtpUsername();
$mail->Password   = $access_details->getSecureSmtpPassword();
$mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port       = $access_details->getSecureSmtpServerPort();

列出收件箱

收件箱列表是分页的。

<?php
public function test_canListInboxes(): void
{
    // create an inbox controller with config
    $inboxController = new MailSlurp\Apis\InboxControllerApi(null, $this->config);

    $pageInboxes = $inboxController->getAllInboxes($favourite = null, $page = 0, $size = 20);

    // assert pagination properties
    $this->assertEquals(0, $pageInboxes->getNumber());
    $this->assertEquals(20, $pageInboxes->getSize());
    $this->assertGreaterThan(0, $pageInboxes->getTotalElements());

    // access inboxes via content
    foreach ($pageInboxes->getContent() as $inbox) {
        $this->assertNotNull($inbox->getId());
    }
}

使用更多选项发送电子邮件

要发送电子邮件,首先创建一个收件箱。然后使用InboxController上的sendEmail方法,并传入发送者收件箱的ID和电子邮件选项。

<?php
public function test_canSendEmail(): void
{
    // create a new inbox
    $inboxController = new MailSlurp\Apis\InboxControllerApi(null, $this->config);
    $inbox = $inboxController->createInbox();

    // send options
    $sendOptions = new MailSlurp\Models\SendEmailOptions();
    $sendOptions->setTo([$inbox->getEmailAddress()]);
    $sendOptions->setSubject("Welcome");
    $sendOptions->setIsHtml(true);
    // (you can use normal strings too)
    $sendOptions->setBody(<<<EOF
        <html>
            <h1>MailSlurp supports HTML</h1>
        </html>
    EOF);

    // send
    $inboxController->sendEmail($inbox->getId(), $sendOptions);
}

附件

在PHP中使用附件非常简单。要发送附件,您必须首先上传每个文件并存储返回的附件ID。要发送,请使用这些ID与SendEmailOptions一起使用。收到的电子邮件附件可以通过EmailControllerApi下载。

<?php
private function uploadAttachment(): array
{
    // a path to some file you want to attach
    $pathToAttachment = $this->pathToAttachment;

    // read file contents
    $contents = file_get_contents($pathToAttachment);

    // encode the file contents to a base64 encoded string for uploading
    $base64Contents = base64_encode($contents);

    // extract file name from path
    $filename = basename($pathToAttachment);
    
    // get the mime type from the file name
    $contentType =  mime_content_type($filename);

    // set upload options
    $uploadOptions = new MailSlurp\Models\UploadAttachmentOptions();
    $uploadOptions->setFilename($filename);
    $uploadOptions->setContentType($contentType);
    $uploadOptions->setBase64Contents($base64Contents);

    // now upload using attachment controller
    $attachmentController = new MailSlurp\Apis\AttachmentControllerApi(null, $this->config);

    // returns [$attachmentId]
    return $attachmentController->uploadAttachment($uploadOptions);
}

要发送附件,可以这样操作

<?php
$attachmentIds = $this->uploadAttachment();

// send options with attachments
$sendOptions = new MailSlurp\Models\SendEmailOptions();
$sendOptions->setTo([$inbox->getEmailAddress()]);
$sendOptions->setSubject("See attached!");
$sendOptions->setAttachments($attachmentIds);

$inboxController->sendEmail($inbox->getId(), $sendOptions);

接收电子邮件

您可以使用MailSlurp在PHP中接收电子邮件。首先创建一个收件箱,然后调用waitFor方法。这些方法会等待新未读电子邮件到达并返回它。

<?php
// get an email in the inbox
$timeout_millis = 10000; // wait at most 10 seconds for new email
$unread_only = true; // only count unread emails

$email = $waitForController->waitForLatestEmail($inbox->getId(), $timeout_millis, $unread_only);

// access email content and properties
print_r($email->getBody())
print_r($email->getSubject())

更大示例

<?php
// create inbox to send from
$inboxController = new MailSlurp\Apis\InboxControllerApi(null, $this->config);

$inbox1= $inboxController->createInbox();
$inbox2 = $inboxController->createInbox();

// send options
$sendOptions = new MailSlurp\Models\SendEmailOptions();
$sendOptions->setTo([$inbox2->getEmailAddress()]);
$sendOptions->setSubject("Here are your files");
$sendOptions->setBody("Hello <strong>JOE</strong>");
$sendOptions->setIsHtml(true);

// send email from inbox 1 to inbox 2 using options above
$inboxController->sendEmail($inbox1->getId(), $sendOptions);

// wait for email to arrive in inbox 2
$waitForController = new MailSlurp\Apis\WaitForControllerApi(null, $this->config);
$email = $waitForController->waitForLatestEmail($inbox_id=$inbox2->getId(), $timeout=30000);

// access email contents
$this->assertEquals($email->getInboxId(), $inbox2->getId());
$this->assertStringContainsString("Here are your files", $email->getSubject());

接收附件

测试示例

<?php
$emailAttachmentId1 = $email->getAttachments()[0];

// download an attachment as base 64 encoded string
$emailController = new MailSlurp\Apis\EmailControllerApi(null, $this->config);
$downloadedAttachment = $emailController->downloadAttachmentBase64($emailAttachmentId1, $email->getId());

$this->assertGreaterThan(0, $downloadedAttachment->getSizeBytes());
$this->assertEquals("text/plain", $downloadedAttachment->getContentType());

// decode file contents
$content = base64_decode($downloadedAttachment->getBase64FileContents());
$this->assertStringContainsString("Sample upload file", $content);

提取电子邮件内容

您可以使用正则表达式以如下方式解析电子邮件正文中的代码或语句

$matches = array();
preg_match('/.+code = (.+)/', $email->getBody(), $matches);
$confirmation_code = $matches[1];
$this->assertEquals($confirmation_code, "abc123");

SDK文档

有关更多功能和示例,请阅读库文档或查看PHP指南