Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Swift Mailer : The missing manual and more.

Swift Mailer : The missing manual and more.

Swift Mailer : The missing manual and more.

Talked at PHP Conference Kansai 2014 in Japan.

http://conference.kphpug.jp/2014/

Sample code:

https://github.com/suzuki/swiftmailer-samples

Norio Suzuki

June 28, 2014
Tweet

More Decks by Norio Suzuki

Other Decks in Technology

Transcript

  1. Agenda • Intro • Basic • Message • Mailer •

    Transport • Plugin • Thirdparty
  2. Intro / About me • Love to get account of

    'suzuki'. • https://twitter.com/suzuki • https://github.com/suzuki
  3. Intro / About me • Career • 2000 - 2012

    Email Service Provider • 2013 - Crocos Inc ! ! • CakePHP2࣮ફೖ໳ (2012-09) • ୈ9ষɿCakeEmailΫϥεΛ࢖ͬͨϝʔϧૹ৴ • http://gihyo.jp/book/2012/978-4-7741-5324-7
  4. Basic / Install • Installed by Composer ! ! •

    composer.json $ php composer.phar require swiftmailer/swiftmailer @stable {! "require": {! "swiftmailer/swiftmailer": "@stable"! }! }
  5. Basic / Structure / Sample // create mailer! $transport =

    Swift_SmtpTransport::newInstance(HOST, PORT);! $mailer = Swift_Mailer::newInstance($transport);! ! // create message! $message = Swift_Message::newInstance();! $message! ->setFrom(MAIL_FROM)! ->setTo(MAIL_TO)! ->setSubject('Hi !')! ->setBody('Hello, Swift Mailer.')! ;! ! // send message! $result = $mailer->send($message); Transport Message Mailer
  6. Message / Header, Body Header / Body code sample From

    $message->setFrom('[email protected]'); Subject $message->setSubject('This is sample'); To, Cc, Bcc $message->setTo('[email protected]')! ->setCc('[email protected]')! ->setBcc('[email protected]');! Body $message->setBody('Hello World');
  7. Message / Headers list Header gettter / setter Message-ID getId()

    / setId()! Return-Path getReturnPath() / serReturnPath()! From getFrom() / setFrom()! Sender getSender() / setSender()! To getTo() / setTo()! Cc getCc() / setCc()! Bcc getBcc() / setBcc()! Reply-To getReplyTo() / setReplyTo()! Subject getSubject() / setSubject()! Date getDate() / setDate()! Content-Type getContentType() / setContentType()! Content-Transfer-Encoding getEncoder() / setEncoder()!
  8. Message / AddPart / Sample $message = Swift_Message::newInstance();! $message! ->setFrom(MAIL_FROM)!

    ->setTo(MAIL_TO)! ->setSubject('Multipart mail sample')! ;! ! // POINT of this sample! $message->addPart(! 'This is TEXT part.',! 'text/plain'! );! $message->addPart(! '<b>This is HTML part.</b>',! 'text/html'! );
  9. Message / Attach / Sample $message = Swift_Message::newInstance();! ! [snip]!

    ! // POINT of this sample! $attachment = Swift_Attachment::fromPath(! './images/panda.jpg',! 'image/jpeg'! );! $message->attach($attachment);
  10. Message / Embed Message ! Body Content-ID: abc123 Embeded File

    <img src="cid:abc123"> embed() “cid” means “Content-ID” via RFC 2557 MHTML
  11. Message / Embed / Sample $message = Swift_Message::newInstance();! ! [snip]!

    ! // POINT of this sample! $embedImage = Swift_Image::fromPath(! './images/panda.jpg'! );! $message->setBody(! '<img src="' . $message->embed($embedImage) . '" />',! 'text/html'! );
  12. Message / S/MIME Message ! Body S/MIME Signature attachSigner() SmimeSigner

    S/MIME signature is like an attached file. It named 'smime.p7s'.
  13. Message / S/MIME / Sample $message = Swift_Message::newInstance();! ! [snip]!

    ! // POINT of this sample! $smimeSigner = Swift_Signers_SMimeSigner::newInstance();! $smimeSigner->setSignCertificate(! SMIME_CERT_FILE,! [SMIME_SECRET_FILE, SMIME_SECRET_PASSPHRASE]! );! $message->attachSigner($smimeSigner);!
  14. Message / DKIM Message Body attachSigner() DKIMSigner Header DKIM Signature

    missing ! DKIM.org http://dkim.org/ http://suzuki.tdiary.net/20140203.html
  15. Message / DKIM / Sample $message = Swift_Message::newInstance();! ! [snip]!

    ! // POINT of this sample! $privateKey = file_get_contents(DKIM_PRIVATE_KEY);! $dkimSigner = Swift_Signers_DKIMSigner::newInstance(! $privateKey,! DKIM_DOMAIN,! DKIM_SELECTOR! );! $message->attachSigner($dkimSigner); missing !
  16. Transport • SMTP • Sendmail, Mail • Failover • Loadbalanced

    • Null • FileSpool, MemorySpool Transport
  17. Transport / SMTP / Samples // POINT of this sample!

    $transport = Swift_SmtpTransport::newInstance(! SMTP_HOST,! SMTP_PORT! );! $mailer = Swift_Mailer::newInstance($transport);
  18. Transport / SMTP / Samples // POINT of this sample!

    $transport = Swift_SmtpTransport::newInstance(! SMTP_AUTH_HOST,! SMTP_AUTH_PORT! );! ! $transport! ->setUsername(SMTP_AUTH_USER)! ->setPassword(SMTP_AUTH_PASS)! ->setEncryption('ssl')! ;! ! $mailer = Swift_Mailer::newInstance($transport);!
  19. Transport / Sendmail / Sample // POINT of this sample!

    $transport = Swift_SendmailTransport::newInstance(! '/usr/sbin/sendmail -bs'! );! // -bs means 'Stand-alone SMTP server mode'! ! $mailer = Swift_Mailer::newInstance($transport);
  20. Transport / Mail / Sample // POINT of this sample!

    $transport = Swift_MailTransport::newInstance();! $mailer = Swift_Mailer::newInstance($transport);! !
  21. Mailer FailoverTransport Transport / Failover missing ! SmtpTransport 1 SMTP

    Server 1 SmtpTransport 2 SmtpTransport n SMTP Server 2 SMTP Server n Usually use SMTP Server1. When Server 1 goes down, use Server 2.
  22. Transport / Failover / Sample // POINT of this sample!

    $transport1 = Swift_SmtpTransport::newInstance(! SMTP_HOST,! SMTP_PORT! );! $transport2 = Swift_SmtpTransport::newInstance(! SMTP_HOST2,! SMTP_PORT2! );! ! $transport = Swift_FailoverTransport::newInstance([! $transport1,! $transport2,! ]);! $mailer = Swift_Mailer::newInstance($transport); missing !
  23. Mailer FailoverTransport Transport / Loadbalanced missing ! SmtpTransport 1 SMTP

    Server 1 SmtpTransport 2 SmtpTransport n SMTP Server 2 SMTP Server n Used in rotation from SMTP Server 1 to STMP Server n
  24. Transport / Loadbalanced / Sample // POINT of this sample!

    $transport1 = Swift_SmtpTransport::newInstance(! SMTP_HOST,! SMTP_PORT! );! $transport2 = Swift_SmtpTransport::newInstance(! SMTP_HOST2,! SMTP_PORT2! );! ! $transport = Swift_LoadBalancedTransport::newInstance([! $transport1,! $transport2,! ]);! $mailer = Swift_Mailer::newInstance($transport); missing !
  25. Transport / Null missing ! ! Mailer NullTransport SMTP Server

    Not send. But counting the number of recipients. Not send
  26. Transport / Null / Sample // POINT of this sample!

    $transport = Swift_NullTransport::newInstance();! $mailer = Swift_Mailer::newInstance($transport); missing !
  27. Transport / FileSpool missing ! Mailer SMTP Server SpoolTransport FileSpool

    Storage File 1 File 2 File 3 File n Not send Create one file by one mail. ! Each files are Swift_Message serialized object.
  28. Transport / FileSpool / Sample // POINT of this sample!

    $path = FILE_SPOOL_PATH;! $spool = new Swift_FileSpool($path);! $transport = Swift_SpoolTransport::newInstance($spool);! ! $mailer = Swift_Mailer::newInstance($transport);! missing !
  29. Transport / MemorySpool missing ! Mailer SMTP Server SpoolTransport MemorySpool

    Memory $array[0] $array[1] $array[3] $array[n] Not send Add one element to array by one mail.
  30. Transport / MemorySpool / Sample // POINT of this sample!

    $spool = new Swift_MemorySpool();! $transport = Swift_SpoolTransport::newInstance($spool);! ! $mailer = Swift_Mailer::newInstance($transport);! missing !
  31. Plugin • AntiFlood • Throttler • Logger • Decorator •

    Impersonate • Redirecting • Reporter Plugin
  32. Plugin / AntiFlood ! Mailer SmtpTransport SMTP Server AntiFloodPlugin Re-connect

    to SMTP Server in every 100 emails (100 is default). You may want to sleep a specified number of seconds. re-connect
  33. Plugin / AntiFlood / Sample // POINT of this sample!

    // re-connect by 1 send, and 10 sec sleep (option)! $mailer->registerPlugin(! new Swift_Plugins_AntiFloodPlugin(1, 10)! );
  34. Plugin / Throttler ! Mailer SmtpTransport SMTP Server ThrottlerPlugin This

    can limit the number of transmissions per minute, second or bytes. ex. 100 mails per minute
  35. Plugin / Throttler / Sample // POINT of this sample!

    // 1 send per minute! $mailer->registerPlugin(! new Swift_Plugins_ThrottlerPlugin(! 1,! ɹɹ Swift_Plugins_ThrottlerPlugin::MESSAGES_PER_MINUTE! )! );
  36. Plugin / Logger Mailer SmtpTransport SMTP Server LoggerPlugin ArrayLogger Display

    logs used dump() method. Logging to array. EchoLogger or Echo each process log.
  37. Plugin / Logger / Sample // POINT of this sample!

    // store log to array! $logger = new Swift_Plugins_Loggers_ArrayLogger();! $mailer->registerPlugin(! new Swift_Plugins_LoggerPlugin($logger)! );! ! [snip]
 
 $result = $mailer->send($message);! ! // POINT of this sample! echo $logger->dump();
  38. Plugin / Decorator $replacements = [! '[email protected]' => [! '{username}'

    => 'Norio Suzuki',! ],! '[email protected]' => [! '{username}' => 'Foo Bar',! ],! ]; To: [email protected] ! Hi, {username} To: [email protected] ! Hi, {username} To: [email protected] ! Hi, Norio Suzuki To: [email protected] ! Hi, Foo Bar replace keywords for each recipients
  39. Plugin / Decorator / Sample // POINT of this sample!

    $replacements = [! MAIL_TO => [! '{username}' => 'USER NAME1',! ],! MAIL_TO2 => [! '{username}' => 'USER NAME2',! ],! ];! $decorator = new Swift_Plugins_DecoratorPlugin($replacements);! $mailer->registerPlugin($decorator);! ! $message = Swift_Message::newInstance();! $message! ->setFrom(MAIL_FROM)! ->setSubject('Info for {username}, Decorator Plugin sample')! ->setBody('Hi, {username}. This is a mail.')! ;
  40. Plugin / Impersonate missing ! ! Mailer SmtpTransport SMTP Server

    ImpersonatePlugin Replace Return-Path address.
  41. Plugin / Impersonate example.com SMTP Server example.jp SMTP Server errors.example.jp

    SMTP Server Bounced mails return to errors.example.jp Using ImpersonatePlugin
  42. Plugin / Impersonate / Sample // POINT of this sample!

    // Replace 'Return-path' to $sender! $sender = MAIL_SENDER;! $mailer->registerPlugin(! new Swift_Plugins_ImpersonatePlugin($sender)! ); missing !
  43. Plugin / Redirecting missing ! ! Mailer SmtpTransport SMTP Server

    RedirectingPlugin All recipients are redirected to specific address.
  44. Plugin / Redirecting Return-Path: [email protected] From: [email protected] To: [email protected] !

    This is a mail. Return-Path: [email protected] From: [email protected] To: [email protected] ! This is a mail. Not replace if exist in whitelist. $whitelist = [! '/^white@/',! ];
  45. Plugin / Redirecting / Sample // POINT of this sample!

    // All recipients are replace to $recipient.! // Except a pattern in whitelist.! $recipient = MAIL_REDIRECT_TO;! $whiteList = [WHITE_LIST_PCRE_PATTERN];! ! $mailer->registerPlugin(! new Swift_Plugins_RedirectingPlugin(! $recipient,! $whiteList! )! ); missing !
  46. Plugin / Reporter missing ! Mailer SmtpTransport SMTP Server ReporterPlugin

    HitReporter Find a failed recipients using FailedRecipients() method. HtmlReporter or Reporting success or failed recipients by HTML format.
  47. Plugin / Reporter / Sample // POINT of this sample!

    $reporter = new Swift_Plugins_Reporters_HitReporter();! $mailer->registerPlugin(! new Swift_Plugins_ReporterPlugin($reporter)! );! ! $recipients = [MAIL_TO, MAIL_FAILED_ADDRESS];! foreach ($recipients as $recipient) {! $message->setTo($recipient);! $result = $mailer->send($message);! }! ! // POINT of this sample! $failedRecipients = $reporter->getFailedRecipients();! var_dump($failedRecipients); missing !
  48. Transport / Amazon SES ! Mailer AWSTransport Amazon SES Sending

    email by Amazon SES http://aws.amazon.com/ses/
  49. Transport / Amazon SES / install {! "require": {! "swiftmailer/swiftmailer":

    "@stable",! "jmhobbs/swiftmailer-transport-aws-ses": "dev-master"! }! } composer.json
  50. Transport / Amazon SES / Sample // POINT of this

    sample! $transport = Swift_AWSTransport::newInstance(! AWS_ACCESS_KEY,! AWS_SECRET_KEY! );! $transport->setEndpoint(AWS_ENDPOINT);! $mailer = Swift_Mailer::newInstance($transport);
  51. Plugin / Filter / install {! "require": {! "swiftmailer/swiftmailer": "@stable",!

    "openbuildings/swiftmailer-filter": "dev-master"! }! } composer.json
  52. Plugin / Filter / Sample use Openbuildings\Swiftmailer\FilterPlugin;! ! [snip]! !

    // POINT of this sample! // set email address or domain! $whiteList = [MAIL_TO];! $blackList = [MAIL_TO2];! $mailer->registerPlugin(! new FilterPlugin($whiteList, $blackList)! );
  53. Plugin / CSS Inliner ! Mailer SmtpTransport SMTP Server CssInlinerPluginPlugin

    Convert to "inline CSS" from CSS written in <style> tag.
  54. Plugin / CSS Inliner <style> .main { background-color: #f9ba34; text-align:

    center; height: 200px; line-height: 200px; } </style> <div class="main"> <h1>Hi, This is CSS Inliner sample</h1> </div> <style> .main { background-color: #f9ba34; text-align: center; height: 200px; line-height: 200px; } </style> <div class="main" style="background-color: #f9ba34; text-align: center;
 height: 200px; line-height: 200px;"> <h1>Hi, This is CSS Inliner sample</h1> </div>
  55. Plugin / CSS Inliner / install {! "require": {! "swiftmailer/swiftmailer":

    "@stable",! "openbuildings/swiftmailer-css-inliner": "dev-master"! }! } composer.json
  56. Plugin / CSS Inliner / Sample use Openbuildings\Swiftmailer\CssInlinerPlugin;! ! [snip]!

    ! // POINT of this sample! $mailer->registerPlugin(! new CssInlinerPlugin()! );!
  57. Plugin / Google Campaign To: [email protected] ! <a href="http://example.com"> example.com

    </a> Add Google Analytics parameters To: [email protected] ! <a href="http://example.com/? utm_source=source&utm_campaign=email&utm_medium=email"> example.com </a>
  58. Plugin / Google Campaign / install {! "require": {! "swiftmailer/swiftmailer":

    "@stable",! "openbuildings/swiftmailer-google-campaign": "dev-master"! }! } composer.json
  59. Plugin / Google Campaign / Sample use Openbuildings\Swiftmailer\GoogleCampaignPlugin;! ! //

    POINT of this sample! $mailer->registerPlugin(! new GoogleCampaignPlugin([! 'utm_source' => 'source',! 'utm_campaign' => 'email',! 'utm_medium' => 'email',! ])! );
  60. Appendix name URL Swift Mailer http://swiftmailer.org/ Amazon SES Transport https://github.com/jmhobbs/Swiftmailer-Transport--AWS-SES

    Filter Plugin https://github.com/OpenBuildings/swiftmailer-filter CSS Inliner Plugin https://github.com/OpenBuildings/swiftmailer-css-inliner Google Campaign Plugin https://github.com/OpenBuildings/swiftmailer-google-campaign Composer https://getcomposer.org/ Packagist https://packagist.org/