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. Swift Mailer
    The missing manual and more.
    PHP Conference Kansai 2014

    2014-06-28

    @suzuki

    View Slide

  2. Agenda
    • Intro
    • Basic
    • Message
    • Mailer
    • Transport
    • Plugin
    • Thirdparty

    View Slide

  3. Intro / About me
    • Love to get account of 'suzuki'.
    • https://twitter.com/suzuki
    • https://github.com/suzuki

    View Slide

  4. Intro / About me
    I receive some mentions

    about SUZUKI motorcar,
    every day.

    View Slide

  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

    View Slide

  6. Intro
    This slide is not related to the series of O'Reilly.

    View Slide

  7. Basic
    • Overview
    • Install
    • Structure

    View Slide

  8. Basic / Overview
    Swift Mailer
    Free Feature

    rich PHP Mailer
    http://swiftmailer.org/

    View Slide

  9. Basic / Install
    • Installed by Composer
    !
    !
    • composer.json
    $ php composer.phar require swiftmailer/swiftmailer @stable
    {!
    "require": {!
    "swiftmailer/swiftmailer": "@stable"!
    }!
    }

    View Slide

  10. Basic / Structure
    Message Mailer

    View Slide

  11. Basic / Structure
    !
    Mailer
    Transport
    Plugin

    View Slide

  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

    View Slide

  13. Message
    • Header, Body
    • AddPart
    • Attach
    • Embed
    • S/MIME
    • DKIM
    Message

    View Slide

  14. Message / Header, Body
    !
    Message
    Header
    Body

    View Slide

  15. 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');

    View Slide

  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()!

    View Slide

  17. Message
    Message / AddPart
    !
    Body
    TextPart
    HtmlPart
    addPart()
    addPart()

    View Slide

  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(!
    'This is HTML part.',!
    'text/html'!
    );

    View Slide

  19. Message / Attach
    Message
    !
    Body
    File attach()

    View Slide

  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);

    View Slide

  21. Message / Embed
    Message
    !
    Body
    Content-ID: abc123
    Embeded File

    embed()
    “cid” means “Content-ID” via RFC 2557 MHTML

    View Slide

  22. Message / Embed / Sample
    $message = Swift_Message::newInstance();!
    !
    [snip]!
    !
    // POINT of this sample!
    $embedImage = Swift_Image::fromPath(!
    './images/panda.jpg'!
    );!
    $message->setBody(!
    '',!
    'text/html'!
    );

    View Slide

  23. Message / S/MIME
    Message
    !
    Body
    S/MIME Signature attachSigner()
    SmimeSigner
    S/MIME signature is like an attached file. It named 'smime.p7s'.

    View Slide

  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);!

    View Slide

  25. Message / DKIM
    Message
    Body
    attachSigner()
    DKIMSigner
    Header
    DKIM Signature
    missing !
    DKIM.org http://dkim.org/ http://suzuki.tdiary.net/20140203.html

    View Slide

  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 !

    View Slide

  27. Mailer
    • Transport
    • Plugin
    !
    Mailer
    Transport
    Plugin

    View Slide

  28. Transport
    • SMTP
    • Sendmail, Mail
    • Failover
    • Loadbalanced
    • Null
    • FileSpool, MemorySpool
    Transport

    View Slide

  29. Transport / SMTP
    !
    Mailer
    SmtpTransport
    SMTP Server

    View Slide

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

    View Slide

  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);!

    View Slide

  32. Transport / Sendmail, Mail
    !
    Mailer
    SendmailTransport,

    MailTransport
    SMTP Server /usr/sbin/sendmail,

    mail()

    View Slide

  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);

    View Slide

  34. Transport / Mail / Sample
    // POINT of this sample!
    $transport = Swift_MailTransport::newInstance();!
    $mailer = Swift_Mailer::newInstance($transport);!
    !

    View Slide

  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.

    View Slide

  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 !

    View Slide

  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

    View Slide

  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 !

    View Slide

  39. Transport / Null
    missing !
    !
    Mailer
    NullTransport
    SMTP Server
    Not send. But counting the number of recipients.
    Not send

    View Slide

  40. Transport / Null / Sample
    // POINT of this sample!
    $transport = Swift_NullTransport::newInstance();!
    $mailer = Swift_Mailer::newInstance($transport);
    missing !

    View Slide

  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.

    View Slide

  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 !

    View Slide

  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.

    View Slide

  44. Transport / MemorySpool / Sample
    // POINT of this sample!
    $spool = new Swift_MemorySpool();!
    $transport = Swift_SpoolTransport::newInstance($spool);!
    !
    $mailer = Swift_Mailer::newInstance($transport);!
    missing !

    View Slide

  45. Plugin
    • AntiFlood
    • Throttler
    • Logger
    • Decorator
    • Impersonate
    • Redirecting
    • Reporter
    Plugin

    View Slide

  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

    View Slide

  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)!
    );

    View Slide

  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

    View Slide

  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!
    )!
    );

    View Slide

  50. Plugin / Logger
    Mailer
    SmtpTransport
    SMTP Server
    LoggerPlugin
    ArrayLogger
    Display logs used dump() method.
    Logging to array.
    EchoLogger
    or
    Echo each process log.

    View Slide

  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();

    View Slide

  52. Plugin / Decorator
    !
    Mailer
    SmtpTransport
    SMTP Server
    DecoratorPlugin
    Replace keywords for each recipients.

    View Slide

  53. 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

    View Slide

  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.')!
    ;

    View Slide

  55. Plugin / Impersonate
    missing !
    !
    Mailer
    SmtpTransport
    SMTP Server
    ImpersonatePlugin
    Replace Return-Path address.

    View Slide

  56. Plugin / Impersonate
    Return-Path: [email protected]
    From: [email protected]
    To: [email protected]
    !
    This is a mail.
    Replace Return-Path
    Return-Path: [email protected]
    From: [email protected]
    To: [email protected]
    !
    This is a mail.

    View Slide

  57. Plugin / Impersonate
    example.com
    SMTP Server
    example.jp
    SMTP Server
    Bounced mails return to
    example.jp
    Normally

    View Slide

  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

    View Slide

  59. Plugin / Impersonate / Sample
    // POINT of this sample!
    // Replace 'Return-path' to $sender!
    $sender = MAIL_SENDER;!
    $mailer->registerPlugin(!
    new Swift_Plugins_ImpersonatePlugin($sender)!
    );
    missing !

    View Slide

  60. Plugin / Redirecting
    missing !
    !
    Mailer
    SmtpTransport
    SMTP Server
    RedirectingPlugin
    All recipients are redirected to specific address.

    View Slide

  61. 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.
    Replace recipients

    View Slide

  62. 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@/',!
    ];

    View Slide

  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 !

    View Slide

  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.

    View Slide

  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 !

    View Slide

  66. Thirdparty
    • Transport
    • Amazon SES
    • Plugin
    • Filter
    • CSS Inliner
    • Google Campaign

    View Slide

  67. Transport / Amazon SES
    !
    Mailer
    AWSTransport
    Amazon SES
    Sending email by Amazon SES
    http://aws.amazon.com/ses/

    View Slide

  68. Transport / Amazon SES / install
    {!
    "require": {!
    "swiftmailer/swiftmailer": "@stable",!
    "jmhobbs/swiftmailer-transport-aws-ses": "dev-master"!
    }!
    }
    composer.json

    View Slide

  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);

    View Slide

  70. Plugin / Filter
    !
    Mailer
    SmtpTransport
    SMTP Server
    FilterPlugin
    Filtering recipients using whitelist and blacklist.

    View Slide

  71. Plugin / Filter / install
    {!
    "require": {!
    "swiftmailer/swiftmailer": "@stable",!
    "openbuildings/swiftmailer-filter": "dev-master"!
    }!
    }
    composer.json

    View Slide

  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)!
    );

    View Slide

  73. Plugin / CSS Inliner
    !
    Mailer
    SmtpTransport
    SMTP Server
    CssInlinerPluginPlugin
    Convert to "inline CSS" from CSS written in tag.<br/>

    View Slide

  74. Plugin / CSS Inliner
    <br/>.main {<br/>background-color: #f9ba34; text-align: center;<br/>height: 200px; line-height: 200px;<br/>}<br/>

    Hi, This is CSS Inliner sample

    <br/>.main {<br/>background-color: #f9ba34; text-align: center;<br/>height: 200px; line-height: 200px;<br/>}<br/>

    Hi, This is CSS Inliner sample

    View Slide

  75. Plugin / CSS Inliner
    Without CSS Inliner plugin (Gmail)
    With CSS Inliner plugin (Gmail)

    View Slide

  76. Plugin / CSS Inliner / install
    {!
    "require": {!
    "swiftmailer/swiftmailer": "@stable",!
    "openbuildings/swiftmailer-css-inliner": "dev-master"!
    }!
    }
    composer.json

    View Slide

  77. Plugin / CSS Inliner / Sample
    use Openbuildings\Swiftmailer\CssInlinerPlugin;!
    !
    [snip]!
    !
    // POINT of this sample!
    $mailer->registerPlugin(!
    new CssInlinerPlugin()!
    );!

    View Slide

  78. Plugin / Google Campaign
    !
    Mailer
    SmtpTransport
    SMTP Server
    GoogleCampaignPluginPlugin
    Add parameters of Google Analytics to each URLs.

    View Slide

  79. Plugin / Google Campaign
    To: [email protected]
    !

    example.com

    Add Google Analytics parameters
    To: [email protected]
    !

    example.com

    View Slide

  80. Plugin / Google Campaign / install
    {!
    "require": {!
    "swiftmailer/swiftmailer": "@stable",!
    "openbuildings/swiftmailer-google-campaign": "dev-master"!
    }!
    }
    composer.json

    View Slide

  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',!
    ])!
    );

    View Slide

  82. Appendix
    • All sample codes are here:
    • https://github.com/suzuki/swiftmailer-samples

    View Slide

  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/

    View Slide

  84. Thank you.

    View Slide