Magento Send Email Via SendGrid

SendGrid’s documentation suggest using the ASchroder.com SMTP Pro Email free extension, but for some reason it didn’t want to install even though it supports the Magento version I have. After a little digging it turns out that there is one simple method to override in Magento Core, that will allow you to upgrade without losing your changes and send via SendGrid.

Change APP to the name or your app

/app/etc/modules/APP_SendGrid.xml

<?xml version="1.0"?>
<config>
	<modules>
		<APP_SendGrid>
			<active>true</active>
			<codePool>local</codePool>
		</APP_SendGrid>
	</modules>
</config>

/app/code/local/APP/SendGrid/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <APP_SendGrid>
            <version>0.1.0</version>
        </APP_SendGrid>
    </modules>
    <global>
        <models>
            <core>
                <rewrite>
                    <email_template>APP_SendGrid_Core_Model_Email_Template</email_template>
                </rewrite>
            </core>
        </models>
    </global>
</config>

/app/code/local/APP/SendGrid/Core/Model/Email/Template.php

<?php
/**
 * extend magento getMail so that we can use the SendGrid smtp servers
 */

class APP_SendGrid_Core_Model_Email_Template extends Mage_Core_Model_Email_Template {

    /**
     * Retrieve mail object instance
     *
     * @return Zend_Mail
     */
    public function getMail() {
        if (is_null($this->_mail)) {
            $config    = array(
                'ssl'      => 'tls',
                'port'     => 587,
                'auth'     => 'login',
                'username' => '<username>',
                'password' => '<password>'
            );
            $transport = new Zend_Mail_Transport_Smtp('smtp.sendgrid.net', $config);
            Zend_Mail::setDefaultTransport($transport);

            $this->_mail = new Zend_Mail('utf-8');

            // set a reporting category
            $category = array('category' => '<category>');
            $this->_mail->addHeader('X-SMTPAPI', json_encode($category, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP));
        }
        return $this->_mail;
    }
}

Once you have those three files in place, you can clear the Magento cache and see if the extension has been recognized.
Go to Magento Admin -> System -> Config -> Advanced and there you will see APP_SendGrid enabled.

Testing

Once you have verified that the module is installed, logout and send yourself a forgot password email. The simplest way to test emails from Magento.

Related Posts