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

8e528456ff66ec543952daa815353a01?s=128

Norio Suzuki

June 28, 2014
Tweet

Transcript

  1. Swift Mailer The missing manual and more. PHP Conference Kansai

    2014 2014-06-28 @suzuki
  2. Agenda • Intro • Basic • Message • Mailer •

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

    'suzuki'. • https://twitter.com/suzuki • https://github.com/suzuki
  4. Intro / About me I receive some mentions
 about SUZUKI

    motorcar, every day.
  5. 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
  6. Intro This slide is not related to the series of

    O'Reilly.
  7. Basic • Overview • Install • Structure

  8. Basic / Overview Swift Mailer Free Feature
 rich PHP Mailer

    http://swiftmailer.org/
  9. Basic / Install • Installed by Composer ! ! •

    composer.json $ php composer.phar require swiftmailer/swiftmailer @stable {! "require": {! "swiftmailer/swiftmailer": "@stable"! }! }
  10. Basic / Structure Message Mailer

  11. Basic / Structure ! Mailer Transport Plugin

  12. 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
  13. Message • Header, Body • AddPart • Attach • Embed

    • S/MIME • DKIM Message
  14. Message / Header, Body ! Message Header Body

  15. Message / Header, Body Header / Body code sample From

    $message->setFrom('suzuki@example.com'); Subject $message->setSubject('This is sample'); To, Cc, Bcc $message->setTo('suzuki+to@example.com')! ->setCc('suzuki+cc@example.com')! ->setBcc('suzuki+bcc@example.com');! Body $message->setBody('Hello World');
  16. 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()!
  17. Message Message / AddPart ! Body TextPart HtmlPart addPart() addPart()

  18. 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'! );
  19. Message / Attach Message ! Body File attach()

  20. Message / Attach / Sample $message = Swift_Message::newInstance();! ! [snip]!

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

    <img src="cid:abc123"> embed() “cid” means “Content-ID” via RFC 2557 MHTML
  22. 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'! );
  23. Message / S/MIME Message ! Body S/MIME Signature attachSigner() SmimeSigner

    S/MIME signature is like an attached file. It named 'smime.p7s'.
  24. 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);!
  25. Message / DKIM Message Body attachSigner() DKIMSigner Header DKIM Signature

    missing ! DKIM.org http://dkim.org/ http://suzuki.tdiary.net/20140203.html
  26. 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 !
  27. Mailer • Transport • Plugin ! Mailer Transport Plugin

  28. Transport • SMTP • Sendmail, Mail • Failover • Loadbalanced

    • Null • FileSpool, MemorySpool Transport
  29. Transport / SMTP ! Mailer SmtpTransport SMTP Server

  30. Transport / SMTP / Samples // POINT of this sample!

    $transport = Swift_SmtpTransport::newInstance(! SMTP_HOST,! SMTP_PORT! );! $mailer = Swift_Mailer::newInstance($transport);
  31. 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);!
  32. Transport / Sendmail, Mail ! Mailer SendmailTransport,
 MailTransport SMTP Server

    /usr/sbin/sendmail,
 mail()
  33. 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);
  34. Transport / Mail / Sample // POINT of this sample!

    $transport = Swift_MailTransport::newInstance();! $mailer = Swift_Mailer::newInstance($transport);! !
  35. 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.
  36. 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 !
  37. 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
  38. 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 !
  39. Transport / Null missing ! ! Mailer NullTransport SMTP Server

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

    $transport = Swift_NullTransport::newInstance();! $mailer = Swift_Mailer::newInstance($transport); missing !
  41. 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.
  42. 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 !
  43. 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.
  44. Transport / MemorySpool / Sample // POINT of this sample!

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

    Impersonate • Redirecting • Reporter Plugin
  46. 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
  47. 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)! );
  48. Plugin / Throttler ! Mailer SmtpTransport SMTP Server ThrottlerPlugin This

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

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

    logs used dump() method. Logging to array. EchoLogger or Echo each process log.
  51. 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();
  52. Plugin / Decorator ! Mailer SmtpTransport SMTP Server DecoratorPlugin Replace

    keywords for each recipients.
  53. Plugin / Decorator $replacements = [! 'suzuki@example.com' => [! '{username}'

    => 'Norio Suzuki',! ],! 'foo@example.com' => [! '{username}' => 'Foo Bar',! ],! ]; To: suzuki@example.com ! Hi, {username} To: foo@example.com ! Hi, {username} To: suzuki@example.com ! Hi, Norio Suzuki To: foo@example.com ! Hi, Foo Bar replace keywords for each recipients
  54. 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.')! ;
  55. Plugin / Impersonate missing ! ! Mailer SmtpTransport SMTP Server

    ImpersonatePlugin Replace Return-Path address.
  56. Plugin / Impersonate Return-Path: sender@example.jp From: sender@example.jp To: suzuki@example.com !

    This is a mail. Replace Return-Path Return-Path: noreply@errors.example.jp From: sender@example.jp To: suzuki@example.com ! This is a mail.
  57. Plugin / Impersonate example.com SMTP Server example.jp SMTP Server Bounced

    mails return to example.jp Normally
  58. Plugin / Impersonate example.com SMTP Server example.jp SMTP Server errors.example.jp

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

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

    RedirectingPlugin All recipients are redirected to specific address.
  61. Plugin / Redirecting Return-Path: sender@example.jp From: sender@example.jp To: suzuki@example.com !

    This is a mail. Return-Path: sender@example.jp From: sender@example.jp To: developer@example.jp ! This is a mail. Replace recipients
  62. Plugin / Redirecting Return-Path: sender@example.jp From: sender@example.jp To: white@example.com !

    This is a mail. Return-Path: sender@example.jp From: sender@example.jp To: white@example.com ! This is a mail. Not replace if exist in whitelist. $whitelist = [! '/^white@/',! ];
  63. 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 !
  64. 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.
  65. 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 !
  66. Thirdparty • Transport • Amazon SES • Plugin • Filter

    • CSS Inliner • Google Campaign
  67. Transport / Amazon SES ! Mailer AWSTransport Amazon SES Sending

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

    "@stable",! "jmhobbs/swiftmailer-transport-aws-ses": "dev-master"! }! } composer.json
  69. 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);
  70. Plugin / Filter ! Mailer SmtpTransport SMTP Server FilterPlugin Filtering

    recipients using whitelist and blacklist.
  71. Plugin / Filter / install {! "require": {! "swiftmailer/swiftmailer": "@stable",!

    "openbuildings/swiftmailer-filter": "dev-master"! }! } composer.json
  72. 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)! );
  73. Plugin / CSS Inliner ! Mailer SmtpTransport SMTP Server CssInlinerPluginPlugin

    Convert to "inline CSS" from CSS written in <style> tag.
  74. 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>
  75. Plugin / CSS Inliner Without CSS Inliner plugin (Gmail) With

    CSS Inliner plugin (Gmail)
  76. Plugin / CSS Inliner / install {! "require": {! "swiftmailer/swiftmailer":

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

    ! // POINT of this sample! $mailer->registerPlugin(! new CssInlinerPlugin()! );!
  78. Plugin / Google Campaign ! Mailer SmtpTransport SMTP Server GoogleCampaignPluginPlugin

    Add parameters of Google Analytics to each URLs.
  79. Plugin / Google Campaign To: suzuki@example.com ! <a href="http://example.com"> example.com

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

    "@stable",! "openbuildings/swiftmailer-google-campaign": "dev-master"! }! } composer.json
  81. 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',! ])! );
  82. Appendix • All sample codes are here: • https://github.com/suzuki/swiftmailer-samples

  83. 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/
  84. Thank you.