ElasticEmailTransport.php 2.7 KB
<?php

namespace FootyRoom\Services\Mail;

use FootyRoom\Config;
use Swift_Transport;
use Swift_Mime_SimpleMessage;
use Illuminate\Mail\Transport\Transport;

class ElasticEmailTransport extends Transport implements Swift_Transport
{
    public function __construct(Config $config)
    {
        $this->apiUser = $config->get('elasticEmail.user');
        $this->apiKey = $config->get('elasticEmail.apiKey');
    }

    /**
     * {@inheritdoc}
     */
    public function isStarted()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function start()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function stop()
    {
        return true;
    }

    public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
    {
        $bodyHtml = '';
        $bodyText = '';

        $from = key($message->getFrom());
        $fromName = $message->getFrom()[$from];

        if ($message->getContentType() === 'text/html') {
            $bodyHtml = $message->getBody();
        } else {
            $bodyText = $message->getBody();
        }

        if (count($message->getChildren())) {
            $child = $message->getChildren()[0];

            if ($child->getContentType() === 'text/plain') {
                $bodyText = $child->getBody();
            }
        }

        $data = 'username='.urlencode($this->apiUser);
        $data .= '&api_key='.urlencode($this->apiKey);

        $data .= '&from='.urlencode($from);
        $data .= '&from_name='.urlencode($fromName);

        $data .= '&to='.urlencode(key($message->getTo()));
        $data .= '&subject='.urlencode($message->getSubject());

        if ($message->getReplyTo()) {
            $replyTo = key($message->getReplyTo());
            $replyToName = $message->getReplyTo()[$replyTo];

            $data .= '&reply_to='.urlencode($replyTo);
            $data .= '&reply_to_name='.urlencode($replyToName);
        }

        if ($bodyHtml) {
            $data .= '&body_html='.urlencode($bodyHtml);
        }

        if ($bodyText) {
            $data .= '&body_text='.urlencode($bodyText);
        }

        $header = "POST /mailer/send HTTP/1.0\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= 'Content-Length: '.strlen($data)."\r\n\r\n";
        $fp = fsockopen('ssl://api.elasticemail.com', 443, $errno, $errstr, 30);

        if (!$fp) {
            return false;
        } else {
            fputs($fp, $header.$data);

            $res = '';
            while (!feof($fp)) {
                $res .= fread($fp, 1024);
            }

            fclose($fp);
        }

        if (substr($res, 9, 3) === '200') {
            return true;
        }
    }
}