Wednesday, January 13, 2016

PHPMailer SMTP in Prestashop

I was using the Mail::Send static function in PrestaShop to send some messages with attachments, but PrestaShop was "decorating" the emails with an attached shop logo image. It also did not allow multiple BCCs.

Rather than override the Mail::Send function, I decided to use Composer to install an updated library to provide flexibility both now and in the future.

As many people have commented, PrestaShop uses an outdated version of SwiftMailer. My initial idea was to simply install a current version in my composer directory (leaving PrestaShop alone), but first I took a look at what libraries people recommended. PHPMailer and SwiftMailer are both very popular (and both apparently work just fine), but PHPMailer seems to be more popular. A comment that I read indicating that debugging PHPMailer was MUCH easier than debugging SwiftMailer, which lead me to decided on PHPMailer.

I used my old article to guide my PHPMailer installation, and then used my configured SMTP params to send email. Worked like a charm... multiple BCCs and attachments included. Below is the SMTP setup using the PrestaShop config. Note that this ONLY works if you set "Set my own SMTP parameters (for advanced users ONLY)" with valid SMTP values in the "Advanced Parameter" / "E-Mails" section of your PrestaShop admin area.

<?php
require(_PS_ROOT_DIR_ . '{location of your autoload file}/autoload.php');
use PHPMailer\PHPMailer\PHPMailer;

function getConfiguredPHPMailer()
{
    $configuration = Configuration::getMultiple(array (
        'PS_MAIL_METHOD',
        'PS_MAIL_SERVER',
        'PS_MAIL_USER',
        'PS_MAIL_PASSWD',
        'PS_MAIL_SMTP_ENCRYPTION',
        'PS_MAIL_SMTP_PORT'
    ), null, null, Context::getContext()->shop->id);

    // Returns immediatly if emails are deactivated
    if ($configuration['PS_MAIL_METHOD'] == 3) {
        return null;
    } else {
        if ($configuration['PS_MAIL_METHOD'] != 2) {
            @mail('you@yoursite.com', 'ERROR: Code only configured for SMTP',
                'Code only works with PrestaShop configured for SMTP (with PS_MAIL_METHOD == 2)');
            return null;
        }
    }

    $mail = new PHPMailer;
    $mail->isSMTP();                                 // Set mailer to use SMTP
    $mail->Host = $configuration['PS_MAIL_SERVER'];  // Specify SMTP server
    $mail->SMTPAuth = true;                          // Enable SMTP authentication
    $mail->Username = $configuration['PS_MAIL_USER'];// SMTP username
    $mail->Password = $configuration['PS_MAIL_PASSWD'];// SMTP password
    $mail->SMTPSecure = $configuration['PS_MAIL_SMTP_ENCRYPTION'];// Enable encryption
    $mail->Port = $configuration['PS_MAIL_SMTP_PORT'];// TCP port to connect to

    return $mail;
}
Post a Comment