【メモ】Swift_Mailerのメール送信の返り値


<?php
$transport = Swift_SmtpTransport::newInstance('localhost',25);
$mailer = Swift_Mailer::newInstance($transport);
$transport = \Swift_SmtpTransport::newInstance('smtp.gmail.com',587,'tls')
->setUsername($from)
->setPassword($password);
$mailer = \Swift_Mailer::newInstance($transport);
$message = \Swift_Message::newInstance()
->setSubject('テストメール')
->setFrom([$from => '送信者名 (省略可)'])
->setTo([$to => '受信者名 (省略可)'])
->setBody("テスト送信です。");
$result = $mailer->send($message);


Swiftでメールを送信したときの返り値がなんなのかよくわからなかったので、ソースを追ってみたメモ。

返り値の実体は「Swift/Transport/AbstractSmtpTransport.php」の175行目ぐらいにあります。


<?php
try {
$sent += $this->_sendTo($message, $reversePath, $to, $failedRecipients);
$sent += $this->_sendCc($message, $reversePath, $cc, $failedRecipients);
$sent += $this->_sendBcc($message, $reversePath, $bcc, $failedRecipients);
} catch (Exception $e) {
$message->setBcc($bcc);
throw $e;
}


つまり、

  • Toだけなら1が、CcまたはBccが追加されていれば2が、両方追加されていたら3が返ります。
  • メール送信の過程で失敗した場合は0が返ります。

ということ。


まとめ

様々なサンプルを見る限り、返り値が真ならメール送信成功としていて実際それでいいと思うんですが、返り値は実は1か2か3かのどれかを取ってますよという話でした。まあ、区別するほどの返り値じゃなかったですね。