Php class для отправки писем через SMTP используя phpmailer

21.02.2019 09:24:08

Простой но полезный класс для отправки писем с вложениями на php.

Для работы нужно проинсталировать phpmailer

 
composer require phpmailer/phpmailer

Пример вызова:

index.php (Download)

 <?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');

require_once('vendor/autoload.php');
require_once ('mailer.php');

$oMailer = new \SOLib\mailer\mailer([
    'SMTPDebug' => 1,
    'SMTPSecure' => 'ssl', // tls
    'Host' => 'smtp.yandex.ru',
    'Port' => 465, // 587
    'Username' => 'no@oddler.ru',
    'Password' => 'PASS',
    'CharSet' => 'UTF-8'
]);


$bRet = $oMailer->send('oddler@oddler.ru,test@oddler.ru',
    'My ТЕСТ 1',
    '<h1>Тест!</h1><p>123</p>',
    [
        'attachments' => [
            __DIR__.'/media/Doc.docx',
            __DIR__.'/media/Тест2.docx'
        ]
    ]
);

if ($bRet){
    echo 'Ok';
}
else {
    echo $oMailer->printDebugOutput();
}

echo "\n\r<br />";
var_dump($bRet);


Код класса:

mailer.php (Download)

 <?php
namespace SOLib\mailer;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class mailer
{
    /**
     * Config
     *
     * @var array
     */
    protected $_aConfig = [];

    /**
     * Debug message buffer
     *
     * @var array
     */
    protected $_aDebugOutput = [];

    /**
     * Log File
     *
     * @var string
     */
    protected $_sLogFile = 'log.txt';

    /**
     * mailer constructor.
     * @param array $aConfig
     */
    public function __construct($aConfig){
        $this->_aConfig = $aConfig;
    }

    /**
     * Return data from config
     *
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    protected function _configGet($key, $default){
        return isset($this->_aConfig[$key])?$this->_aConfig[$key]:$default;
    }

    /**
     * Adds debug information to the buffer.
     * @param string $str
     * @param int $level
     */
    protected function _addDebugOutput($str, $level){
        $this->_aDebugOutput[] = $level.': '.$str;
    }

    /**
     * Returns an error messages.
     *
     * @return array
     */
    public function getDebugOutput(){
        return $this->_aDebugOutput;
    }

    /**
     * Generates output error message.
     * @return string
     */
    public function printDebugOutput(){
        $sBR = PHP_SAPI == 'cli'?"\n\r":'<br />';
        $sRet = '<pre>';
        if (count($this->_aDebugOutput)){
            foreach ($this->_aDebugOutput as $sLine){
                $sRet .=  htmlspecialchars($sLine).$sBR;
            }
        }
        else {
            $sRet .= '-';
        }



        return $sRet.'</pre>';
    }

    /**
     * Add text 2 log
     * @param string $sText
     *
     * @return void
     */
    protected function _add2Log($sText) {
        $sFile = $this->_sLogFile;
        $sDate = date('Y/m/d h:i:s');
        $sRet = file_get_contents($sFile) ."\r\n----------\r\n". $sDate.' '.$sText;
        file_put_contents($sFile, $sRet);
    }

    /**
     * Sends email messages
     *
     * @param string $sEmails
     * @param string$sSubject
     * @param string $sBody
     * @param array $aOptions
     *
     * @return bool
     */
    public function send($sEmails, $sSubject, $sBody, $aOptions = []){
        $mail = new PHPMailer();
        try {
            $mail->IsSMTP();
            $mail->SMTPAuth      = true;
            $mail->SMTPKeepAlive = true;
            $mail->SMTPDebug = $this->_configGet('SMTPDebug', 1);
            $mail->SMTPSecure = $this->_configGet('SMTPSecure', 'ssl');
            $mail->Host = $this->_configGet('Host', 'smtp.yandex.ru');
            $mail->Port = $this->_configGet('Port', 465);
            $mail->Username = $this->_configGet('Username', '');
            $mail->Password = $this->_configGet('Password', '');
            $mail->CharSet = $this->_configGet('CharSet', 'UTF-8'); // 'Windows-1251'
            $mail->Debugoutput = function($str, $level) {
                $this->_addDebugOutput($str, $level);
            };
            $mail->SetFrom($this->_configGet('SetFrom', $mail->Username));

            $aEmails = explode(',', $sEmails);
            foreach($aEmails as $sEmail) {
                $mail->AddAddress(trim($sEmail));
            }

            if (isset($aOptions['attachments'])){
                if(is_array($aOptions['attachments'])) {
                    foreach($aOptions['attachments'] as $fname) {
                        $mail->AddAttachment($fname);
                    }
                } else {
                    $mail->AddAttachment($aOptions['attachments']);
                }
            }

            $mail->Subject = $sSubject;
            $mail->MsgHTML($sBody);

            if(!$mail->Send()) {
                $bRet = FALSE;
            }
            else {
                $bRet = TRUE;
            }
            $mail->ClearAddresses();
            $mail->ClearAttachments();

            return $bRet;

        } catch (Exception $e) {
            die('Message could not be sent. Mailer Error: '. $mail->ErrorInfo);
        }
    }
}


Категории: PHP, Script / Tool
Яндекс.Метрика