[ Index ]

MailPress 7.1

[ Index ]     [ Classes ]     [ Functions ]     [ Variables ]     [ Constants ]     [ Statistics ]    

title

Body

[close]

/mp-includes/composer/vendor/swiftmailer/swiftmailer/doc/ -> sending.rst (source)

   1  Sending Messages
   2  ================
   3  
   4  Quick Reference for Sending a Message
   5  -------------------------------------
   6  
   7  Sending a message is very straightforward. You create a Transport, use it to
   8  create the Mailer, then you use the Mailer to send the message.
   9  
  10  When using ``send()`` the message will be sent just like it would be sent if
  11  you used your mail client. An integer is returned which includes the number of
  12  successful recipients. If none of the recipients could be sent to then zero
  13  will be returned, which equates to a boolean ``false``. If you set two ``To:``
  14  recipients and three ``Bcc:`` recipients in the message and all of the
  15  recipients are delivered to successfully then the value 5 will be returned::
  16  
  17      // Create the Transport
  18      $transport = (new Swift_SmtpTransport('smtp.example.org', 25))
  19        ->setUsername('your username')
  20        ->setPassword('your password')
  21        ;
  22  
  23      /*
  24      You could alternatively use a different transport such as Sendmail:
  25  
  26      // Sendmail
  27      $transport = new Swift_SendmailTransport('/usr/sbin/sendmail -bs');
  28      */
  29  
  30      // Create the Mailer using your created Transport
  31      $mailer = new Swift_Mailer($transport);
  32  
  33      // Create a message
  34      $message = (new Swift_Message('Wonderful Subject'))
  35        ->setFrom(['john@doe.com' => 'John Doe'])
  36        ->setTo(['receiver@domain.org', 'other@domain.org' => 'A name'])
  37        ->setBody('Here is the message itself')
  38        ;
  39  
  40      // Send the message
  41      $result = $mailer->send($message);
  42  
  43  Transport Types
  44  ~~~~~~~~~~~~~~~
  45  
  46  Transports are the classes in Swift Mailer that are responsible for
  47  communicating with a service in order to deliver a Message. There are several
  48  types of Transport in Swift Mailer, all of which implement the
  49  ``Swift_Transport`` interface::
  50  
  51  * ``Swift_SmtpTransport``: Sends messages over SMTP; Supports Authentication;
  52    Supports Encryption. Very portable; Pleasingly predictable results; Provides
  53    good feedback;
  54  
  55  * ``Swift_SendmailTransport``: Communicates with a locally installed
  56    ``sendmail`` executable (Linux/UNIX). Quick time-to-run; Provides
  57    less-accurate feedback than SMTP; Requires ``sendmail`` installation;
  58  
  59  * ``Swift_LoadBalancedTransport``: Cycles through a collection of the other
  60    Transports to manage load-reduction. Provides graceful fallback if one
  61    Transport fails (e.g. an SMTP server is down); Keeps the load on remote
  62    services down by spreading the work;
  63  
  64  * ``Swift_FailoverTransport``: Works in conjunction with a collection of the
  65    other Transports to provide high-availability. Provides graceful fallback if
  66    one Transport fails (e.g. an SMTP server is down).
  67  
  68  The SMTP Transport
  69  ..................
  70  
  71  The SMTP Transport sends messages over the (standardized) Simple Message
  72  Transfer Protocol. It can deal with encryption and authentication.
  73  
  74  The SMTP Transport, ``Swift_SmtpTransport`` is without doubt the most commonly
  75  used Transport because it will work on 99% of web servers (I just made that
  76  number up, but you get the idea). All the server needs is the ability to
  77  connect to a remote (or even local) SMTP server on the correct port number
  78  (usually 25).
  79  
  80  SMTP servers often require users to authenticate with a username and password
  81  before any mail can be sent to other domains. This is easily achieved using
  82  Swift Mailer with the SMTP Transport.
  83  
  84  SMTP is a protocol -- in other words it's a "way" of communicating a job to be
  85  done (i.e. sending a message). The SMTP protocol is the fundamental basis on
  86  which messages are delivered all over the internet 7 days a week, 365 days a
  87  year. For this reason it's the most "direct" method of sending messages you can
  88  use and it's the one that will give you the most power and feedback (such as
  89  delivery failures) when using Swift Mailer.
  90  
  91  Because SMTP is generally run as a remote service (i.e. you connect to it over
  92  the network/internet) it's extremely portable from server-to-server. You can
  93  easily store the SMTP server address and port number in a configuration file
  94  within your application and adjust the settings accordingly if the code is
  95  moved or if the SMTP server is changed.
  96  
  97  Some SMTP servers -- Google for example -- use encryption for security reasons.
  98  Swift Mailer supports using both SSL and TLS encryption settings.
  99  
 100  Using the SMTP Transport
 101  ^^^^^^^^^^^^^^^^^^^^^^^^
 102  
 103  The SMTP Transport is easy to use. Most configuration options can be set with
 104  the constructor.
 105  
 106  To use the SMTP Transport you need to know which SMTP server your code needs to
 107  connect to. Ask your web host if you're not sure. Lots of people ask me who to
 108  connect to -- I really can't answer that since it's a setting that's extremely
 109  specific to your hosting environment.
 110  
 111  A connection to the SMTP server will be established upon the first call to
 112  ``send()``::
 113  
 114      // Create the Transport
 115      $transport = new Swift_SmtpTransport('smtp.example.org', 25);
 116  
 117      // Create the Mailer using your created Transport
 118      $mailer = new Swift_Mailer($transport);
 119  
 120      /*
 121      It's also possible to use multiple method calls
 122  
 123      $transport = (new Swift_SmtpTransport())
 124        ->setHost('smtp.example.org')
 125        ->setPort(25)
 126        ;
 127      */
 128  
 129  Encrypted SMTP
 130  ^^^^^^^^^^^^^^
 131  
 132  You can use SSL or TLS encryption with the SMTP Transport by specifying it as a
 133  parameter or with a method call::
 134  
 135      // Create the Transport
 136      $transport = new Swift_SmtpTransport('smtp.example.org', 587, 'ssl');
 137  
 138      // Create the Mailer using your created Transport
 139      $mailer = new Swift_Mailer($transport);
 140  
 141  A connection to the SMTP server will be established upon the first call to
 142  ``send()``. The connection will be initiated with the correct encryption
 143  settings.
 144  
 145  .. note::
 146  
 147      For SSL or TLS encryption to work your PHP installation must have
 148      appropriate OpenSSL transports wrappers. You can check if "tls" and/or
 149      "ssl" are present in your PHP installation by using the PHP function
 150      ``stream_get_transports()``.
 151  
 152  .. note::
 153      If you are using Mailcatcher_, make sure you do not set the encryption
 154      for the ``Swift_SmtpTransport``, since Mailcatcher does not support encryption.
 155  
 156  SMTP with a Username and Password
 157  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 158  
 159  Some servers require authentication. You can provide a username and password
 160  with ``setUsername()`` and ``setPassword()`` methods::
 161  
 162      // Create the Transport the call setUsername() and setPassword()
 163      $transport = (new Swift_SmtpTransport('smtp.example.org', 25))
 164        ->setUsername('username')
 165        ->setPassword('password')
 166        ;
 167  
 168      // Create the Mailer using your created Transport
 169      $mailer = new Swift_Mailer($transport);
 170  
 171  Your username and password will be used to authenticate upon first connect when
 172  ``send()`` are first used on the Mailer.
 173  
 174  If authentication fails, an Exception of type ``Swift_TransportException`` will
 175  be thrown.
 176  
 177  .. note::
 178  
 179      If you need to know early whether or not authentication has failed and an
 180      Exception is going to be thrown, call the ``start()`` method on the
 181      created Transport.
 182  
 183  The Sendmail Transport
 184  ......................
 185  
 186  The Sendmail Transport sends messages by communicating with a locally installed
 187  MTA -- such as ``sendmail``.
 188  
 189  The Sendmail Transport, ``Swift_SendmailTransport`` does not directly connect
 190  to any remote services. It is designed for Linux servers that have ``sendmail``
 191  installed. The Transport starts a local ``sendmail`` process and sends messages
 192  to it. Usually the ``sendmail`` process will respond quickly as it spools your
 193  messages to disk before sending them.
 194  
 195  The Transport is named the Sendmail Transport for historical reasons
 196  (``sendmail`` was the "standard" UNIX tool for sending e-mail for years). It
 197  will send messages using other transfer agents such as Exim or Postfix despite
 198  its name, provided they have the relevant sendmail wrappers so that they can be
 199  started with the correct command-line flags.
 200  
 201  It's a common misconception that because the Sendmail Transport returns a
 202  result very quickly it must therefore deliver messages to recipients quickly --
 203  this is not true. It's not slow by any means, but it's certainly not faster
 204  than SMTP when it comes to getting messages to the intended recipients. This is
 205  because sendmail itself sends the messages over SMTP once they have been
 206  quickly spooled to disk.
 207  
 208  The Sendmail Transport has the potential to be just as smart of the SMTP
 209  Transport when it comes to notifying Swift Mailer about which recipients were
 210  rejected, but in reality the majority of locally installed ``sendmail``
 211  instances are not configured well enough to provide any useful feedback. As
 212  such Swift Mailer may report successful deliveries where they did in fact fail
 213  before they even left your server.
 214  
 215  You can run the Sendmail Transport in two different modes specified by command
 216  line flags:
 217  
 218  * "``-bs``" runs in SMTP mode so theoretically it will act like the SMTP
 219    Transport
 220  
 221  * "``-t``" runs in piped mode with no feedback, but theoretically faster,
 222    though not advised
 223  
 224  You can think of the Sendmail Transport as a sort of asynchronous SMTP
 225  Transport -- though if you have problems with delivery failures you should try
 226  using the SMTP Transport instead. Swift Mailer isn't doing the work here, it's
 227  simply passing the work to somebody else (i.e. ``sendmail``).
 228  
 229  Using the Sendmail Transport
 230  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 231  
 232  To use the Sendmail Transport you simply need to call ``new
 233  Swift_SendmailTransport()`` with the command as a parameter.
 234  
 235  To use the Sendmail Transport you need to know where ``sendmail`` or another
 236  MTA exists on the server. Swift Mailer uses a default value of
 237  ``/usr/sbin/sendmail``, which should work on most systems.
 238  
 239  You specify the entire command as a parameter (i.e. including the command line
 240  flags). Swift Mailer supports operational modes of "``-bs``" (default) and
 241  "``-t``".
 242  
 243  .. note::
 244  
 245      If you run sendmail in "``-t``" mode you will get no feedback as to whether
 246      or not sending has succeeded. Use "``-bs``" unless you have a reason not to.
 247  
 248  A sendmail process will be started upon the first call to ``send()``. If the
 249  process cannot be started successfully an Exception of type
 250  ``Swift_TransportException`` will be thrown::
 251  
 252      // Create the Transport
 253      $transport = new Swift_SendmailTransport('/usr/sbin/exim -bs');
 254  
 255      // Create the Mailer using your created Transport
 256      $mailer = new Swift_Mailer($transport);
 257  
 258  Available Methods for Sending Messages
 259  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 260  
 261  The Mailer class offers one method for sending Messages -- ``send()``.
 262  
 263  When a message is sent in Swift Mailer, the Mailer class communicates with
 264  whichever Transport class you have chosen to use.
 265  
 266  Each recipient in the message should either be accepted or rejected by the
 267  Transport. For example, if the domain name on the email address is not
 268  reachable the SMTP Transport may reject the address because it cannot process
 269  it. ``send()`` will return an integer indicating the number of accepted
 270  recipients.
 271  
 272  .. note::
 273  
 274      It's possible to find out which recipients were rejected -- we'll cover that
 275      later in this chapter.
 276  
 277  Using the ``send()`` Method
 278  ...........................
 279  
 280  The ``send()`` method of the ``Swift_Mailer`` class sends a message using
 281  exactly the same logic as your Desktop mail client would use. Just pass it a
 282  Message and get a result.
 283  
 284  The message will be sent just like it would be sent if you used your mail
 285  client. An integer is returned which includes the number of successful
 286  recipients. If none of the recipients could be sent to then zero will be
 287  returned, which equates to a boolean ``false``. If you set two
 288  ``To:`` recipients and three ``Bcc:`` recipients in the message and all of the
 289  recipients are delivered to successfully then the value 5 will be returned::
 290  
 291      // Create the Transport
 292      $transport = new Swift_SmtpTransport('localhost', 25);
 293  
 294      // Create the Mailer using your created Transport
 295      $mailer = new Swift_Mailer($transport);
 296  
 297      // Create a message
 298      $message = (new Swift_Message('Wonderful Subject'))
 299        ->setFrom(['john@doe.com' => 'John Doe'])
 300        ->setTo(['receiver@domain.org', 'other@domain.org' => 'A name'])
 301        ->setBody('Here is the message itself')
 302        ;
 303  
 304      // Send the message
 305      $numSent = $mailer->send($message);
 306  
 307      printf("Sent %d messages\n", $numSent);
 308  
 309      /* Note that often that only the boolean equivalent of the
 310         return value is of concern (zero indicates FALSE)
 311  
 312      if ($mailer->send($message))
 313      {
 314        echo "Sent\n";
 315      }
 316      else
 317      {
 318        echo "Failed\n";
 319      }
 320  
 321      */
 322  
 323  Sending Emails in Batch
 324  .......................
 325  
 326  If you want to send a separate message to each recipient so that only their own
 327  address shows up in the ``To:`` field, follow the following recipe:
 328  
 329  * Create a Transport from one of the provided Transports --
 330    ``Swift_SmtpTransport``, ``Swift_SendmailTransport``,
 331    or one of the aggregate Transports.
 332  
 333  * Create an instance of the ``Swift_Mailer`` class, using the Transport as
 334    it's constructor parameter.
 335  
 336  * Create a Message.
 337  
 338  * Iterate over the recipients and send message via the ``send()`` method on
 339    the Mailer object.
 340  
 341  Each recipient of the messages receives a different copy with only their own
 342  email address on the ``To:`` field.
 343  
 344  Make sure to add only valid email addresses as recipients. If you try to add an
 345  invalid email address with ``setTo()``, ``setCc()`` or ``setBcc()``, Swift
 346  Mailer will throw a ``Swift_RfcComplianceException``.
 347  
 348  If you add recipients automatically based on a data source that may contain
 349  invalid email addresses, you can prevent possible exceptions by validating the
 350  addresses using ``Egulias\EmailValidator\EmailValidator`` (a dependency that is
 351  installed with Swift Mailer) and only adding addresses that validate. Another
 352  way would be to wrap your ``setTo()``, ``setCc()`` and ``setBcc()`` calls in a
 353  try-catch block and handle the ``Swift_RfcComplianceException`` in the catch
 354  block.
 355  
 356  Handling invalid addresses properly is especially important when sending emails
 357  in large batches since a single invalid address might cause an unhandled
 358  exception and stop the execution or your script early.
 359  
 360  .. note::
 361  
 362      In the following example, two emails are sent. One to each of
 363      ``receiver@domain.org`` and ``other@domain.org``. These recipients will
 364      not be aware of each other::
 365  
 366          // Create the Transport
 367          $transport = new Swift_SmtpTransport('localhost', 25);
 368  
 369          // Create the Mailer using your created Transport
 370          $mailer = new Swift_Mailer($transport);
 371  
 372          // Create a message
 373          $message = (new Swift_Message('Wonderful Subject'))
 374            ->setFrom(['john@doe.com' => 'John Doe'])
 375            ->setBody('Here is the message itself')
 376            ;
 377  
 378          // Send the message
 379          $failedRecipients = [];
 380          $numSent = 0;
 381          $to = ['receiver@domain.org', 'other@domain.org' => 'A name'];
 382  
 383          foreach ($to as $address => $name)
 384          {
 385            if (is_int($address)) {
 386              $message->setTo($name);
 387            } else {
 388              $message->setTo([$address => $name]);
 389            }
 390  
 391            $numSent += $mailer->send($message, $failedRecipients);
 392          }
 393  
 394          printf("Sent %d messages\n", $numSent);
 395  
 396  Finding out Rejected Addresses
 397  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 398  
 399  It's possible to get a list of addresses that were rejected by the Transport by
 400  using a by-reference parameter to ``send()``.
 401  
 402  As Swift Mailer attempts to send the message to each address given to it, if a
 403  recipient is rejected it will be added to the array. You can pass an existing
 404  array, otherwise one will be created by-reference.
 405  
 406  Collecting the list of recipients that were rejected can be useful in
 407  circumstances where you need to "prune" a mailing list for example when some
 408  addresses cannot be delivered to.
 409  
 410  Getting Failures By-reference
 411  .............................
 412  
 413  Collecting delivery failures by-reference with the ``send()`` method is as
 414  simple as passing a variable name to the method call::
 415  
 416      $mailer = new Swift_Mailer( ... );
 417  
 418      $message = (new Swift_Message( ... ))
 419        ->setFrom( ... )
 420        ->setTo([
 421          'receiver@bad-domain.org' => 'Receiver Name',
 422          'other@domain.org' => 'A name',
 423          'other-receiver@bad-domain.org' => 'Other Name'
 424        ))
 425        ->setBody( ... )
 426        ;
 427  
 428      // Pass a variable name to the send() method
 429      if (!$mailer->send($message, $failures))
 430      {
 431        echo "Failures:";
 432        print_r($failures);
 433      }
 434  
 435      /*
 436      Failures:
 437      Array (
 438        0 => receiver@bad-domain.org,
 439        1 => other-receiver@bad-domain.org
 440      )
 441      */
 442  
 443  If the Transport rejects any of the recipients, the culprit addresses will be
 444  added to the array provided by-reference.
 445  
 446  .. note::
 447  
 448      If the variable name does not yet exist, it will be initialized as an
 449      empty array and then failures will be added to that array. If the variable
 450      already exists it will be type-cast to an array and failures will be added
 451      to it.
 452  
 453  .. _Mailcatcher: https://mailcatcher.me/


Generated: Mon Mar 11 18:33:33 2019 Cross-referenced by PHPXref 0.7.1