我尝试将Paubox与Laravel 5集成为自定义邮件提供程序。 我怎样才能做到最好? 我安装了https://github.com/Paubox/paubox-php机器人,但没有说明如何将其与Laravel连接。
答案 0 :(得分:0)
我通过创建新的服务提供商和Transport类来解决此问题。
// Illuminate\Mail\MailServiceProvider::class,
App\Providers\PauboxServiceProvider::class,
'pauboxApiKey' => env('PAUBOX_API_KEY'),
'pauboxApiUser' => env('PAUBOX_API_USER')
MAIL_DRIVER=paubox
PAUBOX_API_KEY=
PAUBOX_API_USER=
<?php
namespace App\Providers;
use Illuminate\Mail\MailServiceProvider;
class PauboxServiceProvider extends MailServiceProvider {
protected function registerSwiftTransport() {
$this->app->singleton('swift.transport', function ($app) {
return new PauboxTransportManager($app);
});
}
}
<?php
namespace App\Providers;
use Illuminate\Mail\TransportManager;
class PauboxTransportManager extends TransportManager {
protected function createPauboxDriver() {
return new PauboxTransport;
}
}
<?php
namespace App\Providers;
use Illuminate\Mail\Transport\Transport;
use Swift_Mime_SimpleMessage;
use App\Vendors\Paubox as Paubox;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Illuminate\Support\Facades\Log;
class PauboxTransport extends Transport {
protected $config;
public function __construct() {
$this->config = config('mail');
}
public function send(Swift_Mime_SimpleMessage $msg, &$failedRecipients = null) {
$paubox = new Paubox\Paubox($this->config['pauboxApiUser'], $this->config['pauboxApiKey']);
$message = new Paubox\Mail\Message();
$content = new Paubox\Mail\Content();
$header = new Paubox\Mail\Header();
$content->setHtmlText($msg->getBody());
$header->setSubject($msg->getSubject());
$header->setFrom('"' . $this->config['from']['name'] . '" <' . $this->config['from']['address'] . '>');
$header->setReplyTo($this->config['from']['address']);
$recipients = [];
foreach ($msg->getTo() as $to => $val) {
recipients[] = $to;
}
$message->setHeader($header);
$message->setContent($content);
$message->setRecipients($recipients);
$sendMessageResponse = new Paubox\Mail\SendMessageResponse();
$sendMessageResponse = $paubox->sendMessage($message);
$errorMsg = '';
if (isset($sendMessageResponse->errors)) {
foreach ($sendMessageResponse->errors as $error) {
$errorMsg .= json_encode($error);
}
Log::error(PHP_EOL . "Paubox: " . $errorMsg . PHP_EOL);
throw new UnprocessableEntityHttpException('Error occurred while sending email');
}
return $sendMessageResponse;
}
}
public function __construct($pauboxApiUser, $pauboxApiKey)
{
$this->pauboxApiUser = $pauboxApiUser;
$this->pauboxApiKey = $pauboxApiKey;
}
及以下代码:
更改\getenv('PAUBOX_API_USER');
进入$this->pauboxApiUser;
并更改\getenv('PAUBOX_API_KEY');
进入$this->pauboxApiKey;
A还必须安装composer require nategood/httpful