vanchelo/phalcon-mailer

Phalcon 邮件服务

2.0.1 2015-09-07 20:34 UTC

This package is not auto-updated.

Last update: 2024-09-14 15:21:47 UTC


README

英文 | 俄语

Phalcon 邮件服务

适用于 Phalcon 2.0 的便捷邮件发送库。

代码借鉴自 Laravel 4 并针对 Phalcon 进行了适配。

安装

使用 composer

将以下行添加到 composer.json 文件的 require 部分

"vanchelo/phalcon-mailer": "~2.0"

或者通过命令行执行

composer require vanchelo/phalcon-mailer

结果应该类似于这样

{
  "require": {
    "vanchelo/phalcon-mailer": "~2.0"
  }
}

之后,在终端中执行以下命令

composer update

服务初始化

/**
 * Register Mailer Service
 */
$this->di['mailer'] = function() {
    $service = new MailerService();

    return $service->mailer();
};

或者通过服务初始化阶段传递参数

/**
 * Register Mailer Service
 */
$this->di['mailer'] = function() {
    $service = new MailerService([
        'driver' => 'smtp', // mail, sendmail, smtp
        'host'   => 'smtp.email.com',
        'port'   => 587,
        'from'   => [
            'address' => 'no-reply@my-domain.com',
            'name'    => 'My Cool Company',
        ],
        'encryption' => 'tls',
        'username'   => 'no-reply@my-domain.com',
        'password'   => 'some-strong-password',
        'sendmail'   => '/usr/sbin/sendmail -bs',
        // Путь используемый для поиска шаблонов писем
        'viewsDir'   => __DIR__ . '/../app/views/', // optional
    ]);

    return $service->mailer();
};

发送邮件

以下为控制器示例,但不仅限于控制器

$this->mailer->send('emails/xxx', [
    'test' => 'test' // Переменные для передачи в шаблон
], function($message) {
    $message->to('some_email@email.com');
    $message->subject('Test Email');
});

emails/xxx - 邮件模板位于目录 views 中(app/views/emails/xxx.[phtml|volt])

默认情况下,如果容器中注册了服务 view,则库将使用它,因此可以使用任何方便的模板引擎(phtml、volt 等)

配置

默认配置需要在应用程序配置文件 config/config.php 中指定

<?php
return new \Phalcon\Config([
    'mail' => [
        'driver' => 'smtp', // mail, sendmail, smtp
        'host'   => 'smtp.email.com',
        'port'   => 587,
        'from'   => [
            'address' => 'no-reply@my-domain.com',
            'name'    => 'My Cool Company'
        ],
        'encryption' => 'tls',
        'username'   => 'no-reply@my-domain.com',
        'password'   => 'some-strong-password',
        'sendmail'   => '/usr/sbin/sendmail -bs',
        // Путь используемый для поиска шаблонов писем
        'viewsDir'   => __DIR__ . '/../app/views/', // optional
    ],
]);

如果需要,可以将邮件配置移动到单独的配置文件中

更新. 实现了使用 Phalcon 服务队列 Beanstalk 的延迟发送邮件功能

队列(延迟发送邮件)

要延迟发送邮件,您需要在容器中注册服务 queue,例如

use Phalcon\Queue\Beanstalk;

$this->di['queue'] = function () {
    $queue = new Beanstalk();
    $queue->connect(); // ?

    return $queue;
};

以下为延迟发送邮件的示例

$this->mailer->queue('emails/xxx', [
    'test' => 'test' // Переменные для передачи в шаблон
], function($message) {
    $message->to('some_email@email.com');
    $message->subject('Test Email');
});

所有延迟邮件都将放入 mailer 队列(不知道这样做是否正确)

队列处理器示例 https://github.com/vanchelo/phalcon-mailer/blob/master/example/mailer.php