Symfony

Symfonyはメール送信にSwiftMailerを使用しています。詳細についてはsending emails from Symfonyを参照してください。

はじめにparameters.ymlを以下のように編集または追記する必要があります:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
mailer:
class: sfMailer
param:
logging: %SF_LOGGING_ENABLED%
charset: %SF_CHARSET%
delivery_strategy: realtime
transport:
class: Swift_SmtpTransport
param:
host: smtp.sendgrid.net
port: 587
encryption: ~
username: apikey
password: sendgrid_api_key

以上でメールを送信することができるようになります。以下がメール送信の例です:

1
2
3
4
5
6
7
8
9
<?php
$message = Swift_Message::newInstance()
  ->setFrom('from@example.com')
  ->setTo('to@example.com')
  ->setSubject('Subject')
  ->setBody('Body');

$this->getMailer()->send($message);
?>

その他の方法

さらに柔軟性が必要な場合、メールコンテンツの定義にpartialsを利用することができます。以下のようなlib/myEmail.class.phpを追加します。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
class myEmail
{
    /**
     * Library to facilitate email messages being sent out, sendMail deprecated in symfony 1.2
     *
     * @param string $partial - Array with html and text partials ie array('text'=>'textPartial', 'html'=>'htmlPartial')
     * @param array $parameters - Array we will pass into the partials
     * @param string $mailFrom - Email source
     * @param string $mailTo - Email destination
     * @param string $subject - The subject of the email message
     * @param array $sgHeaders - What we will be placing in the SMTPAPI header. Must be null or a non-empty array
     * @param array $attachments - Email contains the attachments
     */

    public static function sendEmail($partials, $parameters, $mailFrom, $mailTo, $subject, $sgHeaders = null, $attachments = null)
    {
        // verify we have username/api_key to send out emails - IMPORTANT
        if (!sfconfig::has('app_sendgrid_username') or !sfconfig::has('app_sendgrid_api_key')) {
            throw new sfException('SMTP username/api_key is required to send email out');
        }
        $text = null;
        $html = null;
        if (is_array($partials)) {
            // load libraries
            sfContext::getInstance()->getConfiguration()->loadHelpers('Partial');
            if (isset($partials['text'])) {
                $text = get_partial($partials['text'], $parameters);
            }
            if (isset($partials['html'])) {
                $html = get_partial($partials['html'], $parameters);
            }
        }
        if ($text === null && $html === null) {
            throw new sfException('A text and/or HTML partial must be given');
        }

        try {
            /*
             * Load connection for mailer
             */
            $connection = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 465, 'ssl')->setUsername(sfconfig::get('app_sendgrid_username'))->setPassword(sfconfig::get('app_sendgrid_api_key'));

            // setup connection/content
            $mailer  = Swift_Mailer::newInstance($connection);
            $message = Swift_Message::newInstance()->setSubject($subject)->setTo($mailTo);

            if ($text && $html) {
                $message->setBody($html, 'text/html');
                $message->addPart($text, 'text/plain');
            } else if ($text) {
                $message->setBody($text, 'text/plain');
            } else {
                $message->setBody($html, 'text/html');
            }

            // if contains SMTPAPI header add it
            if (null !== $sgHeaders) {
                $message->getHeaders()->addTextHeader('X-SMTPAPI', json_encode($sgHeaders));
            }

            // update the from address line to include an actual name
            if (is_array($mailFrom) and count($mailFrom) == 2) {
                $mailFrom = array(
                    $mailFrom['email'] => $mailFrom['name']
                );
            }

            // add attachments to email
            if ($attachments !== null and is_array($attachments)) {
                foreach ($attachments as $attachment) {
                    $attach = Swift_Attachment::fromPath($attachment['file'], $attachment['mime'])->setFilename($attachment['filename']);
                    $message->attach($attach);
                }
            }

            // Send
            $message->setFrom($mailFrom);
            $mailer->send($message);
        }
        catch (Exception $e) {
            throw new sfException('Error sending email out - ' . $e->getMessage());
        }
    }
}
?>

apps/frontend/app.ymlに認証情報を設定します。

1
2
3
4
prod:
sendgrid:
username: apikey
password: sendgrid_api_key

モジュール内(apps/frontend/modules/mail)にpartialsを配置します。例えば、テキストとHTMLで登録メールを送信する場合以下のような構成になります。

1
2
3
4
5
6
apps/
frontend/
modules/
mail/
_registrationHTML.php
_registrationTEXT.php

apps/frontend/modules/mail/_registrationTEXT.phpに以下を追加します。

1
2
Dear <!--?php echo $name ?-->,
Thank you for registering. Please go to http://domain.com to finish your registration.

apps/frontend/modules/mail/_registrationHTML.phpに以下を追加します。

1
2
Dear <!--?php echo $name ?-->,
Thank you for registering. Please go to <a href="http://domain.com">here</a> to finish your registration.

最後に以下のようにメッセージを送信します:

1
2
3
<?php
myEmail::sendEmail(array('text'=>'mail/registrationTEXT', 'html'=>'mail/registrationHTML'), array('name'=>'Recipient Name'), 'youremail@domain.com', 'recipient@example.com', 'Registration Information');
?>