MailGun Api Wrapper to send emails

You are viewing revision #4 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#3)next (#5) »

MailGun.php Class

I will keep updating this at GitHub here: https://gist.github.com/vinaykrsharma/0729d75234fb9cc59e8c

<?php
/**
 * MailGun
 * @author VINAY KUMAR SHARMA <vinaykrsharma@live.in>
 */
class MailGun extends CApplicationComponent {
    /***************************************************************************
                              PUBLIC Properties
    ***************************************************************************/
    
    /**
     * PHP Curl Options, use PHP Curl constant variable to pass.
     * e.g:
     *   CURLOPT_HEADER => TRUE
     *   CURLOPT_USERAGENT => 'Bond/0.0.7'
     * @var array PHP Curl extension options
     */
    public $options = array();
    
    /**
     * Default Sender Address
     * if don't found in send() method parameters
     * 
     * @var string Sender email
     */
    public $defaultFromEmail = 'postmaster@localhost';
    
    /***************************************************************************
                      PRIVATE and PROTECTED Properties
    ***************************************************************************/

    /**
     * The path to the directory where the view for getView is stored. Must not
     * have ending dot.
     *
     * @var string
     */
    protected $pathViews = 'application.views.email';

    /**
     * The path to the directory where the layout for getView is stored. Must
     * not have ending dot.
     *
     * @var string
     */
    protected $pathLayouts = 'application.views.email.layouts';

    protected $httpHeaders = array(
        CURLOPT_HTTPHEADER => array(
            'Accept: application/json',
            'Accept-Language: en-us;q=0.5,en;q=0.3',
            'Accept-Charset: utf-8;q=0.7,*;q=0.7',
            'Keep-Alive: 300'
        ),
    );

    /**
     * @var object curl_init() return value
     */
    private $_ch;
    private $_curlOptions = array(
        CURLOPT_URL => "https://api.mailgun.net/v2/YOURDOMAIN.COM/messages",
        CURLOPT_USERPWD => 'api:key-f82c1b4ebc17cd0afca13a4-21ca935a7', // Set Yours
        CURLOPT_HEADER => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POST => true,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Linux; Ubuntu) MailGun-Curl-Client.in/1.0b'
    );

    public function __construct() {
        
    }

    public function init() {
        parent::init();
        foreach ($this->options as $key => $value) {
            $this->_curlOptions[$key] = $value;
        }
        if (!isset($this->_curlOptions[CURLOPT_USERPWD]) || empty($this->_curlOptions[CURLOPT_USERPWD])) {
            throw new CException('MailGun: Option `CURLOPT_USERPWD` is not found in option');
        }
    }

    /***************************************************************************
                           GETTERS and SETTERS
    ***************************************************************************/

    /**
     * Setter
     *
     * @param string $value pathLayouts
     */
    public function setPathLayouts($value) {
        if (!is_string($value) && !preg_match("/[a-z0-9\.]/i", $value)) {
            throw new CException(Yii::t('MailGun', 'pathLayouts must be a Yii alias path'));
        }
        $this->pathLayouts = $value;
    }

    /**
     * Getter
     *
     * @return string pathLayouts
     */
    public function getPathLayouts() {
        return $this->pathLayouts;
    }

    /**
     * Setter
     *
     * @param string $value pathViews
     */
    public function setPathViews($value) {
        if (!is_string($value) && !preg_match("/[a-z0-9\.]/i", $value)) {
            throw new CException(Yii::t('MailGun', 'pathViews must be a Yii alias path'));
        }
        $this->pathViews = $value;
    }

    /**
     * Getter
     *
     * @return string pathViews
     */
    public function getPathViews() {
        return $this->pathViews;
    }

    /**
     * Displays an e-mail in preview mode. 
     *
     * @param string $view the class
     * @param array $vars Controller->renderPartial() options
     * @param string $layout
     */
    public function getView($view, $vars = array(), $layout = null) {
        $controller = Yii::app()->controller;
        $body = $controller->renderPartial($this->pathViews . '.' . $view,
                $vars, true);
        if ($layout === null) {
            return $body;
        }
        return $controller->renderPartial($this->pathLayouts . '.' . $layout, array('content' => $body), true);
    }

    /**
     * Send Email
     * 
     * @param string $to Send emails to. comma seperate email address for multiple
     * receipients
     * @param string $subject Subject of the Email
     * @param string $html_body HTML Body of the email
     * @param array $extras options
     *  <ul>
     *      <li><strong>from:</strong> Sender Email ID</li>
     *      <li><strong>text:</strong> Alternate email in simple text format</li>
     *      <li><strong>tags:</strong> Tag the email with comma seperated value</li>
     *  </ul>
     */
    public function send($to, $subject, $html_body, $extras = array()) {
        try {
            $this->_ch = curl_init($this->_curlOptions[CURLOPT_URL]);

            $fields = array(
                "from" => $this->defaultFromEmail,
            );
            if (isset($extras['from']) && !empty($extras['from'])) {
                $fields['from'] = & $extras['from'];
            }
            if(empty($fields['from'])) {
                throw new CHttpException('Send Email address can not be null');
            }
            if (empty($to) || strlen($to) < 5) {
                throw new CException('Receipients can not be empty');
            }
            $fields['to'] = & $to;
            $fields['subject'] = & $subject;
            if (!empty($html_body) && strlen($html_body) >= 5) {
                $fields['html'] = & $html_body;
            }
            if (isset($extras['text']) && !empty($extras['text'])) {
                $fields['text'] = & $extras['text'];
            } elseif (isset($fields['html'])) {
                $fields['text'] = strip_tags($fields['html']);
            }
            if (isset($extras['tags']) && !empty($extras['tags'])) {
                $fields['o:tag'] = & $extras['tags'];
            }
            $this->_curlOptions[CURLOPT_POSTFIELDS] = & $fields;
            curl_setopt_array($this->_ch, $this->_curlOptions);

            $response_with_headers = curl_exec($this->_ch);
            curl_close($this->_ch);
            return $response_with_headers;
        } catch (Exception $e) {
            
        }
        return NULL;
    }

}
Add to Yii Config

Add as a component in Yii config files either it could be main.php or console.php (not tested yet)

<?php
    // ...
    'components' => array(
        'mailgun' => array(
            'class' => 'application.components.MailGun',
            'defaultFromEmail' => 'PM Online <no-reply@example.com>',
            'options' => array(
                        CURLOPT_URL => "https://api.mailgun.net/v2/<YOURDOMAIN.COM>/messages",
                CURLOPT_USERPWD => 'api:key-f82c1b4ebc17cd0afca13a4-21ca935a7',
            ),
            'pathLayouts' => 'application.views.layouts.emailer',
            'pathViews' => 'application.views.partials',
        ),
        // ...
    )
    // ...
?>
Now Start sending emails

Here is an test email send

<?php
    $r = Yii::app()->mailgun->send($model->email, 'Hello',
        "<p>Testing from Main App, for some <small style=\"color: green;\">awesomness</span>!</p>");
    if($r) {
        $r = json_decode($r);
    }
?>

In this example I've changed defaultFromEmail and CURLOPT_USERPWD. So find your own and replace. ;)