Composerがない環境でSwiftMailerを利用する


ソースを入手

Gitから入手

  • libを作業ディレクトリにアップロードする

config設定

$config = array(
    'host' => 'smtp.example.com',
    'port' => 465,
    'user' => '[email protected]',
    'pass' => 'password',
    'encryption' => 'ssl',
    'url' => 'http://localhost',
    'mailaddress' => '[email protected]',
    'sendname' => '株式会社Dummy担当',
    'subject_user' => 'お問い合わせありがとうございます',
    'subject_admin' => 'お問い合わせを受信しました',
    'note' => true,  // 送信控え
    'cc' => array(
        '[email protected]',
        '[email protected]',
    ),
    'bcc' => array(
        '[email protected]',
    ),
);

送信処理

    // 日本語に関する初期設定
    Swift::init(function () {
        Swift_DependencyContainer::getInstance()
            ->register('mime.qpheaderencoder')
            ->asAliasOf('mime.base64headerencoder');
        Swift_Preferences::getInstance()->setCharset('iso-2022-jp');
    });

    // SMTPサーバーとの接続設定
    $transport = Swift_SmtpTransport::newInstance($config['host'], $config['port'])
        ->setUsername($config['user'])
        ->setPassword($config['pass'])
        ->setEncryption($config['encryption']);

    $mailer = Swift_Mailer::newInstance($transport);


    // メール情報をセット
    $subject = sprintf($config['subject_admin'], $posts['nameKanji'], $posts['postKind']);
    $body = $body_header_admin.$mail_data['body_middle'].$body_footer_admin;
    $from = array($config['mailaddress'] => $config['sendname']);
    $to = array($config['mailaddress'] => $config['sendname']);

    // メールの作成
    $message = Swift_Message::newInstance();
    $message->setCharset('iso-2022-jp');
    $message->setEncoder(Swift_Encoding::get7BitEncoding());
    $message->setSubject($subject);
    $message->setFrom($from);
    $message->setTo($to);
    if (count($config['cc']) != 0) {
        $message->setCc($config['cc']);
    }
    if (count($config['bcc']) != 0) {
        $message->setBcc($config['bcc']);
    }
    $message->setBody($body, 'text/plain');

    // 送信処理
    $result = $mailer->send($message);

    // 送信控え送信
    if ($config['note'] == true) {
        $subject = $config['subject_user'];
        $body = $body_header_user.$mail_data['body_middle'].$body_footer_user;
        $to = array('[email protected]' => 'dummy');

        $message = Swift_Message::newInstance();
        $message->setCharset('iso-2022-jp');
        $message->setEncoder(Swift_Encoding::get7BitEncoding());
        $message->setSubject($subject);
        $message->setFrom($from);
        $message->setTo($to);
        $message->setBody($body, 'text/plain');

        // 送信処理
        $result = $mailer->send($message);
    }