proxiedmail/php-client

用于处理ProxiedMail API的库

0.6.0 2024-04-18 12:31 UTC

This package is auto-updated.

Last update: 2024-09-10 23:14:13 UTC


README

欢迎使用ProxiedMail API客户端。您可以查看文档

Packagist

特性

🔴 授权

🔴 回调接收器(创建回调URL,读取回调负载)

🔴 代理电子邮件CRUD(创建、读取、更新、待定:删除)

安装

composer require proxiedmail/php-client

测试运行

如果您想运行测试,请确保存在包含凭证的.env文件。复制以下命令

cp .env.dist .env

运行

make test-run

入门:接收应用中的电子邮件

在这个示例中,您可以了解如何接收发送到您的API的电子邮件。程序将打印出用于接收电子邮件消息的电子邮件地址。

PROXY-EMAIL: 4bd6c97b9@proxiedmail.com
Webhook STATUS: 
Received: no

然后,只需将电子邮件发送到打印的地址。当应用收到您的消息时,它将打印以下内容

PROXY-EMAIL: 4bd6c97b9@proxiedmail.com
Webhook STATUS: 
Received: yes
WEBHOOK PAYLOAD: 
{
   "id":"EB442408-D500-0000-00003CC8",
   "payload":{
      "Content-Type":"multipart\/alternative; boundary=\"000000000000714564060f56f6c2\"",
      "Date":"Sat, 20 Jan 2024 02:00:25 +0000",
      "Dkim-Signature":"DKIM",
      "From":"Alex Yatsenko <sender@gmail.com>",
      "Message-Id":"<CAJj9C9dVhSJZDwRDM-H=vhzPttpg253biEvabFtEHiS4wriK8A@mail.gmail.com>",
      "Mime-Version":"1.0",
      "Received":"by mail-wm1-f44.google.com with SMTP id 5b1f17b1804b1-40e9ffab5f2so10064475e9.1 for <4bd6c97b9@proxiedmail.com>; Fri, 19 Jan 2024 18:00:38 -0800 (PST)",
      "Subject":"hey mate",
      "To":"4bd6c97b9@proxiedmail.com",
      "X-Envelope-From":"sender@gmail.com",
      "X-Mailgun-Incoming":"Yes",
      "X-Received":"Received details",
      "body-html":"<div dir=\"ltr\">hey hey<\/div>\r\n",
      "body-plain":"hey hey\r\n",
      "domain":"proxiedmail.com",
      "from":"Alex Alex <sender@gmail.com>",
      "message-headers":"HEADERS JSON....",
      "recipient":"4bd6c97b9@proxiedmail.com",
      "sender":"sender@gmail.com",
      "signature":"....",
      "stripped-html":"<div dir=\"ltr\">hey hey<\/div>\n",
      "stripped-text":"hey hey",
      "subject":"hey mate",
      "timestamp":"1705716046",
      "token":"..."
   },
   "attachments":[
      
   ],
   "recipient":{
      "address":"4bd6c97b9@proxiedmail.com"
   },
   "receivedAt":"Sat Jan 20 2024 02:00:46 GMT+0000",
   "user":{
      "id":"1B3AAA43-11-0000-cc",
      "username":"username+t1@gmail.com",
      "token":"Bearer ...."
   }
}

要执行的代码如下

<?php

use ProxiedMail\Client\Config\Config;
use ProxiedMail\Client\Entities\ResponseEntity\OauthAccessTokenEntity;
use ProxiedMail\Client\Entrypoint\PxdMailApinitializer;
use ProxiedMail\Client\Facades\ApiFacade;

require 'vendor/autoload.php';


// put here your ProxiedMail credentials
$email = 'example@example.com';
$pass = '1';

/**
 * @var ApiFacade $facade
 */
$facade = PxdMailApinitializer::init();
/**
 * @var OauthAccessTokenEntity $r
 */
$r = $facade->login($email, $pass);

//settings bearer token
$config = (new Config())->setBearerToken('Bearer ' . $r->getBearerToken());
$facade = PxdMailApinitializer::init($config);

//receiving API token by bearer token
$apiToken = $facade->getApiToken();

$config = new Config();

//setting API token
$config->setApiToken($apiToken->getApiToken());

$api = PxdMailApinitializer::init($config);

$proxyEmail  = $api->createProxyEmail(
    [],
    null,
    null,
    null,
    true
);



// while (true) with 100 seconds limit
foreach(range(0, 180) as $non) {
    echo "PROXY-EMAIL: " . $proxyEmail->getProxyAddress() . "\n";
    echo "Time limit is 3 mins \n";
    echo "Send the email to this proxy-email to get email payload printed here \n";

    //checking webhook receiver

    $receivedEmails = $api->getReceivedEmailsLinksByProxyEmailId($proxyEmail->getId())->getReceivedEmailLinks();
    echo "Amount of received emails: " . count($receivedEmails) . "\n";
    foreach ($receivedEmails as $receivedEmail) {
        echo "Have received email: \n";
        var_dump($receivedEmail); //you can also receive a payload here. Check out attributes

        echo "\n";
    }

    echo "\n";

    sleep(1);
}

或者如果您更喜欢webhook,您可以尝试以下操作

<?php

use ProxiedMail\Client\Config\Config;
use ProxiedMail\Client\Entities\ResponseEntity\OauthAccessTokenEntity;
use ProxiedMail\Client\Entrypoint\PxdMailApinitializer;
use ProxiedMail\Client\Facades\ApiFacade;

require 'vendor/autoload.php';


// put here your ProxiedMail credentials
$email = 'example.com';
$pass = '1';

/**
 * @var ApiFacade $facade
 */
$facade = PxdMailApinitializer::init();
/**
 * @var OauthAccessTokenEntity $r
 */
$r = $facade->login($email, $pass);

//settings bearer token
$config = (new Config())->setBearerToken('Bearer ' . $r->getBearerToken());
$facade = PxdMailApinitializer::init($config);

//receiving API token by bearer token
$apiToken = $facade->getApiToken();

$config = new Config();

//setting API token
$config->setApiToken($apiToken->getApiToken());

$api = PxdMailApinitializer::init($config);

$wh = $api->createWebhook(); //creating webhook-receiver
$proxyEmail  = $api->createProxyEmail(
    [],
    null,
    $wh->getCallUrl() //specifying webhook url
);



// while (true) with 100 seconds limit
foreach(range(0, 100) as $non) {
    echo "PROXY-EMAIL: " . $proxyEmail->getProxyAddress() . "\n";
    echo "Send the email to this proxy-email to get email payload printed here";
    
    //checking webhook receiver 
    $whStatus = $api->statusWebhook($wh->getId());

    echo "Webhook STATUS: \n";
    echo "Received: " . ($whStatus->isReceived() ? 'yes' : 'no') . "\n"; //printing webhook status

    //printing payload if received
    if ($whStatus->isReceived()) {
        echo "WEBHOOK PAYLOAD: \n";
        echo json_encode($whStatus->getPayload());
        break;
    }


    echo "\n";

    sleep(1);
}

要运行上述示例,只需创建文件夹,使用composer在该文件夹中安装库,并将其放置在文件(t.php)中,然后运行

php t.php

示例

授权

        <?php
        
        use ProxiedMail\Client\Config\Config;
        use ProxiedMail\Client\Entities\ResponseEntity\OauthAccessTokenEntity;
        use ProxiedMail\Client\Entrypoint\PxdMailApinitializer;
        use ProxiedMail\Client\Facades\ApiFacade;
        
        require 'vendor/autoload.php';
        
        $email = $this->envValue('TESTS_AUTH_EMAIL');
        $pass = $this->envValue('TESTS_AUTH_PASSWORD');

        /**
         * @var ApiFacade $facade
         */
        $facade = PxdMailApinitializer::init();
        /**
         * @var OauthAccessTokenEntity $r
         */
        $r = $facade->login($email, $pass);

        $config = (new Config())->setBearerToken('Bearer ' . $r->getBearerToken());
        $facade = PxdMailApinitializer::init($config);

        $apiToken = $facade->getApiToken();

        $config = new Config();
        $config->setApiToken($apiToken->getApiToken());

        $facade = PxdMailApinitializer::init($config)

Webhook

<?php
        //it's $facade from the end of previous example
        $api = $this->getApiReady(); //let's imagine we have ApiFacade here 
        $wh = $api->createWebhook();

        $status = $api->statusWebhook($wh->getId());

        $status->isReceived(); // false
        $status->getMethod(); //null
        $status->getPayload(); //null


        //make a post call to $wh->call_url
        $url = $wh->getCallUrl();
        $data = [
            'key1' => 'value1',
            'key2' => 'value2'
        ];

        $options = [
            'http' => [
                'header' => "Content-type: application/json",
                'method' => 'POST',
                'content' => json_encode($data),
            ],
        ];

        $context = stream_context_create($options);
        file_get_contents($url, false, $context);


        $status = $api->statusWebhook($wh->getId());

        $status->isReceived(); //true;
        $status->getMethod(); //POST
        $status->getPayload(); //same what we have in $data

创建代理电子邮件

<?php
        $api = $this->getApiReady();

        $pb = $api->createProxyEmail(
            [
                'blabla@proxiedmail-int.int',
            ],
            uniqid() . '@proxiedmail.com',
            null,
            null
        );

        $pb->getId(); //string ID, A1131D57-6000-0000-00000BAE
        $pb->getAddressDetailedCollectionEntity(); //@see RealAddressDetailedCollectionEntity::class
        $pb->getProxyAddress(); //blabla@proxiedmail.com
        $pb->getReceivedEmails(); // 0
        $pb->getTypeValue(); // 0 - Regular, 1 - news

代理电子邮件列表

<?php
        $api = $this->getApiReady();
        $wh = $api->getProxyEmails();
        /**
         * @var ProxyBindingEntity $pb
         */
        $pb = $wh->getProxyBindings()[0];

接收到的电子邮件列表

请注意,您只能查看已将is_browsable选项设置为true的代理电子邮件的接收到的电子邮件。即使您还没有接收到的电子邮件,您也可以更新is_browsable属性。

<?php
        $api = $this->getApiReady();
        $api->createProxyEmail(
            [
                $api->generateInternalEmail(),
            ],
            null,
            null,
            null,
            true //opt in is_browsable
        );
        
        $wh = $api->getProxyEmails();
        /**
         * @var ProxyBindingEntity $pb
         */
        $pb = $wh->getProxyBindings()[0]; //pick up the last one we created

        $emailsList = $api->getReceivedEmailsLinksByProxyEmailId($pb->getId());

        $entity = $emailsList->getReceivedEmailLinks()[0];
        $receivedEmailId = $entity->getId();
        $subject = $entity->getSubject();
        $recipientEmail = $entity->getRecipientEmail();
        $attachmentCounter = $entity->getAttachmentsCounter();

        $emailDetails = $api->getReceivedEmailDetailsByReceivedEmailId($entity->getId());
        
        $payload = $email->getPayload();

        $strippedHtml = $payload['stripped-html'];
        $contentType = $payload['Content-Type'];
        $from = $payload['From'];
        $sender = $payload['Sender'];
        $subject = $payload['Subject'];
        $to = $payload['To'];
        $bodyHtml = $payload['body-html'];

还可以尝试简化版本

        $entity = $api->waitUntilNextEmail($pb->getId()); //get by proxy email id
        $payload = $entity->getPayload();

如果您打算使用此功能接收第一封电子邮件,您可以将初始值传递为0,并接收在函数调用之前存在的任何电子邮件。

        $api->internalSendMail('test', $pb->getProxyAddress(), 'Test');
        sleep(5);
        $entity = $api->waitUntilNextEmail($pb->getId(), 60, 1, 0); // id, max tried, timeout sec, initial value

或者与第一封电子邮件一起

        $entity = $api->waitUntilFirstEmail($pb->getId());
        $email = $api->getReceivedEmailDetailsByReceivedEmailId($entity->getId());
        $payload = $email->getPayload();

但请注意,在运行时电子邮件尚未接收。否则,它可能会花费一些时间。

其他示例

您还可以在其他示例中查看https://github.com/proxied-mail/proxiedmail-php-client/tree/main/tests/Integration

授权建议

首先使用您的电子邮件和密码进行授权。然后使用收到的Bearer token接收您的API密钥。

您还可以在ProxiedMail账户的"设置"部分中获取您的API令牌: https://proxiedmail.com/en/settings 。您可以将其硬编码到您的应用程序中,因为它没有过期日期。如果您想撤销它,请告诉我们。

依赖注入

如您所见,我们在客户端中内置了DI,以减少依赖项,因为这是一个单独的类。

<?php
        $api = PxdMailApinitializer::init();
        // OR
        $config = new Config('HOST', 'API_TOKEN', 'Bearer token'); //everything nullable
        $api = PxdMailApinitializer::init($config);

请注意,如果您想在程序执行过程中更改有关主机、Bearer或API令牌的配置,请通过PxdMailApinitializer::init()使用新的配置对象重新初始化。

额外功能

如果您感兴趣,请查看我们的Laravel客户端。文章: 如何在Laravel中接收电子邮件。文章 如何在PHP中接收电子邮件。文章 如何使用PHP或Laravel接收电子邮件