[ Index ] |
MailPress 7.2 |
[ Index ] [ Classes ] [ Functions ] [ Variables ] [ Constants ] [ Statistics ] |
[Summary view] [Print] [Text view]
1 Creating Messages 2 ================= 3 4 Creating messages in Swift Mailer is done by making use of the various MIME 5 entities provided with the library. Complex messages can be quickly created 6 with very little effort. 7 8 Quick Reference 9 --------------- 10 11 You can think of creating a Message as being similar to the steps you perform 12 when you click the Compose button in your mail client. You give it a subject, 13 specify some recipients, add any attachments and write your message:: 14 15 // Create the message 16 $message = (new Swift_Message()) 17 18 // Give the message a subject 19 ->setSubject('Your subject') 20 21 // Set the From address with an associative array 22 ->setFrom(['john@doe.com' => 'John Doe']) 23 24 // Set the To addresses with an associative array (setTo/setCc/setBcc) 25 ->setTo(['receiver@domain.org', 'other@domain.org' => 'A name']) 26 27 // Give it a body 28 ->setBody('Here is the message itself') 29 30 // And optionally an alternative body 31 ->addPart('<q>Here is the message itself</q>', 'text/html') 32 33 // Optionally add any attachments 34 ->attach(Swift_Attachment::fromPath('my-document.pdf')) 35 ; 36 37 Message Basics 38 -------------- 39 40 A message is a container for anything you want to send to somebody else. There 41 are several basic aspects of a message that you should know. 42 43 An e-mail message is made up of several relatively simple entities that are 44 combined in different ways to achieve different results. All of these entities 45 have the same fundamental outline but serve a different purpose. The Message 46 itself can be defined as a MIME entity, an Attachment is a MIME entity, all 47 MIME parts are MIME entities -- and so on! 48 49 The basic units of each MIME entity -- be it the Message itself, or an 50 Attachment -- are its Headers and its body: 51 52 .. code-block:: text 53 54 Header-Name: A header value 55 Other-Header: Another value 56 57 The body content itself 58 59 The Headers of a MIME entity, and its body must conform to some strict 60 standards defined by various RFC documents. Swift Mailer ensures that these 61 specifications are followed by using various types of object, including 62 Encoders and different Header types to generate the entity. 63 64 The Structure of a Message 65 ~~~~~~~~~~~~~~~~~~~~~~~~~~ 66 67 Of all of the MIME entities, a message -- ``Swift_Message`` is the largest and 68 most complex. It has many properties that can be updated and it can contain 69 other MIME entities -- attachments for example -- nested inside it. 70 71 A Message has a lot of different Headers which are there to present information 72 about the message to the recipients' mail client. Most of these headers will be 73 familiar to the majority of users, but we'll list the basic ones. Although it's 74 possible to work directly with the Headers of a Message (or other MIME entity), 75 the standard Headers have accessor methods provided to abstract away the 76 complex details for you. For example, although the Date on a message is written 77 with a strict format, you only need to pass a DateTimeInterface instance to 78 ``setDate()``. 79 80 +-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ 81 | Header | Description | Accessors | 82 +===============================+====================================================================================================================================+=============================================+ 83 | ``Message-ID`` | Identifies this message with a unique ID, usually containing the domain name and time generated | ``getId()`` / ``setId()`` | 84 +-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ 85 | ``Return-Path`` | Specifies where bounces should go (Swift Mailer reads this for other uses) | ``getReturnPath()`` / ``setReturnPath()`` | 86 +-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ 87 | ``From`` | Specifies the address of the person who the message is from. This can be multiple addresses if multiple people wrote the message. | ``getFrom()`` / ``setFrom()`` | 88 +-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ 89 | ``Sender`` | Specifies the address of the person who physically sent the message (higher precedence than ``From:``) | ``getSender()`` / ``setSender()`` | 90 +-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ 91 | ``To`` | Specifies the addresses of the intended recipients | ``getTo()`` / ``setTo()`` | 92 +-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ 93 | ``Cc`` | Specifies the addresses of recipients who will be copied in on the message | ``getCc()`` / ``setCc()`` | 94 +-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ 95 | ``Bcc`` | Specifies the addresses of recipients who the message will be blind-copied to. Other recipients will not be aware of these copies. | ``getBcc()`` / ``setBcc()`` | 96 +-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ 97 | ``Reply-To`` | Specifies the address where replies are sent to | ``getReplyTo()`` / ``setReplyTo()`` | 98 +-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ 99 | ``Subject`` | Specifies the subject line that is displayed in the recipients' mail client | ``getSubject()`` / ``setSubject()`` | 100 +-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ 101 | ``Date`` | Specifies the date at which the message was sent | ``getDate()`` / ``setDate()`` | 102 +-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ 103 | ``Content-Type`` | Specifies the format of the message (usually text/plain or text/html) | ``getContentType()`` / ``setContentType()`` | 104 +-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ 105 | ``Content-Transfer-Encoding`` | Specifies the encoding scheme in the message | ``getEncoder()`` / ``setEncoder()`` | 106 +-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ 107 108 Working with a Message Object 109 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 110 111 Although there are a lot of available methods on a message object, you only 112 need to make use of a small subset of them. Usually you'll use 113 ``setSubject()``, ``setTo()`` and ``setFrom()`` before setting the body of your 114 message with ``setBody()``:: 115 116 $message = new Swift_Message(); 117 $message->setSubject('My subject'); 118 119 All MIME entities (including a message) have a ``toString()`` method that you 120 can call if you want to take a look at what is going to be sent. For example, 121 if you ``echo $message->toString();`` you would see something like this: 122 123 .. code-block:: text 124 125 Message-ID: <1230173678.4952f5eeb1432@swift.generated> 126 Date: Thu, 25 Dec 2008 13:54:38 +1100 127 Subject: Example subject 128 From: Chris Corbyn <chris@w3style.co.uk> 129 To: Receiver Name <recipient@example.org> 130 MIME-Version: 1.0 131 Content-Type: text/plain; charset=utf-8 132 Content-Transfer-Encoding: quoted-printable 133 134 Here is the message 135 136 We'll take a closer look at the methods you use to create your message in the 137 following sections. 138 139 Adding Content to Your Message 140 ------------------------------ 141 142 Rich content can be added to messages in Swift Mailer with relative ease by 143 calling methods such as ``setSubject()``, ``setBody()``, ``addPart()`` and 144 ``attach()``. 145 146 Setting the Subject Line 147 ~~~~~~~~~~~~~~~~~~~~~~~~ 148 149 The subject line, displayed in the recipients' mail client can be set with the 150 ``setSubject()`` method, or as a parameter to ``new Swift_Message()``:: 151 152 // Pass it as a parameter when you create the message 153 $message = new Swift_Message('My amazing subject'); 154 155 // Or set it after like this 156 $message->setSubject('My amazing subject'); 157 158 Setting the Body Content 159 ~~~~~~~~~~~~~~~~~~~~~~~~ 160 161 The body of the message -- seen when the user opens the message -- is specified 162 by calling the ``setBody()`` method. If an alternative body is to be included, 163 ``addPart()`` can be used. 164 165 The body of a message is the main part that is read by the user. Often people 166 want to send a message in HTML format (``text/html``), other times people want 167 to send in plain text (``text/plain``), or sometimes people want to send both 168 versions and allow the recipient to choose how they view the message. 169 170 As a rule of thumb, if you're going to send a HTML email, always include a 171 plain-text equivalent of the same content so that users who prefer to read 172 plain text can do so. 173 174 If the recipient's mail client offers preferences for displaying text vs. HTML 175 then the mail client will present that part to the user where available. In 176 other cases the mail client will display the "best" part it can - usually HTML 177 if you've included HTML:: 178 179 // Pass it as a parameter when you create the message 180 $message = new Swift_Message('Subject here', 'My amazing body'); 181 182 // Or set it after like this 183 $message->setBody('My <em>amazing</em> body', 'text/html'); 184 185 // Add alternative parts with addPart() 186 $message->addPart('My amazing body in plain text', 'text/plain'); 187 188 Attaching Files 189 --------------- 190 191 Attachments are downloadable parts of a message and can be added by calling the 192 ``attach()`` method on the message. You can add attachments that exist on disk, 193 or you can create attachments on-the-fly. 194 195 Although we refer to files sent over e-mails as "attachments" -- because 196 they're attached to the message -- lots of other parts of the message are 197 actually "attached" even if we don't refer to these parts as attachments. 198 199 File attachments are created by the ``Swift_Attachment`` class and then 200 attached to the message via the ``attach()`` method on it. For all of the 201 "every day" MIME types such as all image formats, word documents, PDFs and 202 spreadsheets you don't need to explicitly set the content-type of the 203 attachment, though it would do no harm to do so. For less common formats you 204 should set the content-type -- which we'll cover in a moment. 205 206 Attaching Existing Files 207 ~~~~~~~~~~~~~~~~~~~~~~~~ 208 209 Files that already exist, either on disk or at a URL can be attached to a 210 message with just one line of code, using ``Swift_Attachment::fromPath()``. 211 212 You can attach files that exist locally, or if your PHP installation has 213 ``allow_url_fopen`` turned on you can attach files from other 214 websites. 215 216 The attachment will be presented to the recipient as a downloadable file with 217 the same filename as the one you attached:: 218 219 // Create the attachment 220 // * Note that you can technically leave the content-type parameter out 221 $attachment = Swift_Attachment::fromPath('/path/to/image.jpg', 'image/jpeg'); 222 223 // Attach it to the message 224 $message->attach($attachment); 225 226 // The two statements above could be written in one line instead 227 $message->attach(Swift_Attachment::fromPath('/path/to/image.jpg')); 228 229 // You can attach files from a URL if allow_url_fopen is on in php.ini 230 $message->attach(Swift_Attachment::fromPath('http://site.tld/logo.png')); 231 232 Setting the Filename 233 ~~~~~~~~~~~~~~~~~~~~ 234 235 Usually you don't need to explicitly set the filename of an attachment because 236 the name of the attached file will be used by default, but if you want to set 237 the filename you use the ``setFilename()`` method of the Attachment. 238 239 The attachment will be attached in the normal way, but meta-data sent inside 240 the email will rename the file to something else:: 241 242 // Create the attachment and call its setFilename() method 243 $attachment = Swift_Attachment::fromPath('/path/to/image.jpg') 244 ->setFilename('cool.jpg'); 245 246 // Because there's a fluid interface, you can do this in one statement 247 $message->attach( 248 Swift_Attachment::fromPath('/path/to/image.jpg')->setFilename('cool.jpg') 249 ); 250 251 Attaching Dynamic Content 252 ~~~~~~~~~~~~~~~~~~~~~~~~~ 253 254 Files that are generated at runtime, such as PDF documents or images created 255 via GD can be attached directly to a message without writing them out to disk. 256 Use ``Swift_Attachment`` directly. 257 258 The attachment will be presented to the recipient as a downloadable file 259 with the filename and content-type you specify:: 260 261 // Create your file contents in the normal way, but don't write them to disk 262 $data = create_my_pdf_data(); 263 264 // Create the attachment with your data 265 $attachment = new Swift_Attachment($data, 'my-file.pdf', 'application/pdf'); 266 267 // Attach it to the message 268 $message->attach($attachment); 269 270 271 // You can alternatively use method chaining to build the attachment 272 $attachment = (new Swift_Attachment()) 273 ->setFilename('my-file.pdf') 274 ->setContentType('application/pdf') 275 ->setBody($data) 276 ; 277 278 .. note:: 279 280 If you would usually write the file to disk anyway you should just attach 281 it with ``Swift_Attachment::fromPath()`` since this will use less memory. 282 283 Changing the Disposition 284 ~~~~~~~~~~~~~~~~~~~~~~~~ 285 286 Attachments just appear as files that can be saved to the Desktop if desired. 287 You can make attachment appear inline where possible by using the 288 ``setDisposition()`` method of an attachment. 289 290 The attachment will be displayed within the email viewing window if the mail 291 client knows how to display it:: 292 293 // Create the attachment and call its setDisposition() method 294 $attachment = Swift_Attachment::fromPath('/path/to/image.jpg') 295 ->setDisposition('inline'); 296 297 298 // Because there's a fluid interface, you can do this in one statement 299 $message->attach( 300 Swift_Attachment::fromPath('/path/to/image.jpg')->setDisposition('inline') 301 ); 302 303 .. note:: 304 305 If you try to create an inline attachment for a non-displayable file type 306 such as a ZIP file, the mail client should just present the attachment as 307 normal. 308 309 Embedding Inline Media Files 310 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 311 312 Often, people want to include an image or other content inline with a HTML 313 message. It's easy to do this with HTML linking to remote resources, but this 314 approach is usually blocked by mail clients. Swift Mailer allows you to embed 315 your media directly into the message. 316 317 Mail clients usually block downloads from remote resources because this 318 technique was often abused as a mean of tracking who opened an email. If 319 you're sending a HTML email and you want to include an image in the message 320 another approach you can take is to embed the image directly. 321 322 Swift Mailer makes embedding files into messages extremely streamlined. You 323 embed a file by calling the ``embed()`` method of the message, 324 which returns a value you can use in a ``src`` or 325 ``href`` attribute in your HTML. 326 327 Just like with attachments, it's possible to embed dynamically generated 328 content without having an existing file available. 329 330 The embedded files are sent in the email as a special type of attachment that 331 has a unique ID used to reference them within your HTML attributes. On mail 332 clients that do not support embedded files they may appear as attachments. 333 334 Although this is commonly done for images, in theory it will work for any 335 displayable (or playable) media type. Support for other media types (such as 336 video) is dependent on the mail client however. 337 338 Embedding Existing Files 339 ........................ 340 341 Files that already exist, either on disk or at a URL can be embedded in a 342 message with just one line of code, using ``Swift_EmbeddedFile::fromPath()``. 343 344 You can embed files that exist locally, or if your PHP installation has 345 ``allow_url_fopen`` turned on you can embed files from other websites. 346 347 The file will be displayed with the message inline with the HTML wherever its ID 348 is used as a ``src`` attribute:: 349 350 // Create the message 351 $message = new Swift_Message('My subject'); 352 353 // Set the body 354 $message->setBody( 355 '<html>' . 356 ' <body>' . 357 ' Here is an image <img src="' . // Embed the file 358 $message->embed(Swift_Image::fromPath('image.png')) . 359 '" alt="Image" />' . 360 ' Rest of message' . 361 ' </body>' . 362 '</html>', 363 'text/html' // Mark the content-type as HTML 364 ); 365 366 // You can embed files from a URL if allow_url_fopen is on in php.ini 367 $message->setBody( 368 '<html>' . 369 ' <body>' . 370 ' Here is an image <img src="' . 371 $message->embed(Swift_Image::fromPath('http://site.tld/logo.png')) . 372 '" alt="Image" />' . 373 ' Rest of message' . 374 ' </body>' . 375 '</html>', 376 'text/html' 377 ); 378 379 .. note:: 380 381 ``Swift_Image`` and ``Swift_EmbeddedFile`` are just aliases of one another. 382 ``Swift_Image`` exists for semantic purposes. 383 384 .. note:: 385 386 You can embed files in two stages if you prefer. Just capture the return 387 value of ``embed()`` in a variable and use that as the ``src`` attribute:: 388 389 // If placing the embed() code inline becomes cumbersome 390 // it's easy to do this in two steps 391 $cid = $message->embed(Swift_Image::fromPath('image.png')); 392 393 $message->setBody( 394 '<html>' . 395 ' <body>' . 396 ' Here is an image <img src="' . $cid . '" alt="Image" />' . 397 ' Rest of message' . 398 ' </body>' . 399 '</html>', 400 'text/html' // Mark the content-type as HTML 401 ); 402 403 Embedding Dynamic Content 404 ......................... 405 406 Images that are generated at runtime, such as images created via GD can be 407 embedded directly to a message without writing them out to disk. Use the 408 standard ``new Swift_Image()`` method. 409 410 The file will be displayed with the message inline with the HTML wherever its ID 411 is used as a ``src`` attribute:: 412 413 // Create your file contents in the normal way, but don't write them to disk 414 $img_data = create_my_image_data(); 415 416 // Create the message 417 $message = new Swift_Message('My subject'); 418 419 // Set the body 420 $message->setBody( 421 '<html>' . 422 ' <body>' . 423 ' Here is an image <img src="' . // Embed the file 424 $message->embed(new Swift_Image($img_data, 'image.jpg', 'image/jpeg')) . 425 '" alt="Image" />' . 426 ' Rest of message' . 427 ' </body>' . 428 '</html>', 429 'text/html' // Mark the content-type as HTML 430 ); 431 432 .. note:: 433 434 ``Swift_Image`` and ``Swift_EmbeddedFile`` are just aliases of one another. 435 ``Swift_Image`` exists for semantic purposes. 436 437 .. note:: 438 439 You can embed files in two stages if you prefer. Just capture the return 440 value of ``embed()`` in a variable and use that as the ``src`` attribute:: 441 442 // If placing the embed() code inline becomes cumbersome 443 // it's easy to do this in two steps 444 $cid = $message->embed(new Swift_Image($img_data, 'image.jpg', 'image/jpeg')); 445 446 $message->setBody( 447 '<html>' . 448 ' <body>' . 449 ' Here is an image <img src="' . $cid . '" alt="Image" />' . 450 ' Rest of message' . 451 ' </body>' . 452 '</html>', 453 'text/html' // Mark the content-type as HTML 454 ); 455 456 Adding Recipients to Your Message 457 --------------------------------- 458 459 Recipients are specified within the message itself via ``setTo()``, ``setCc()`` 460 and ``setBcc()``. Swift Mailer reads these recipients from the message when it 461 gets sent so that it knows where to send the message to. 462 463 Message recipients are one of three types: 464 465 * ``To:`` recipients -- the primary recipients (required) 466 467 * ``Cc:`` recipients -- receive a copy of the message (optional) 468 469 * ``Bcc:`` recipients -- hidden from other recipients (optional) 470 471 Each type can contain one, or several addresses. It's possible to list only the 472 addresses of the recipients, or you can personalize the address by providing 473 the real name of the recipient. 474 475 Make sure to add only valid email addresses as recipients. If you try to add an 476 invalid email address with ``setTo()``, ``setCc()`` or ``setBcc()``, Swift 477 Mailer will throw a ``Swift_RfcComplianceException``. 478 479 If you add recipients automatically based on a data source that may contain 480 invalid email addresses, you can prevent possible exceptions by validating the 481 addresses using:: 482 use Egulias\EmailValidator\EmailValidator; 483 use Egulias\EmailValidator\Validation\RFCValidation; 484 485 $validator = new EmailValidator(); 486 $validator->isValid("example@example.com", new RFCValidation()); //true 487 and only adding addresses that validate. Another way would be to wrap your ``setTo()``, ``setCc()`` and 488 ``setBcc()`` calls in a try-catch block and handle the 489 ``Swift_RfcComplianceException`` in the catch block. 490 491 .. sidebar:: Syntax for Addresses 492 493 If you only wish to refer to a single email address (for example your 494 ``From:`` address) then you can just use a string:: 495 496 $message->setFrom('some@address.tld'); 497 498 If you want to include a name then you must use an associative array:: 499 500 $message->setFrom(['some@address.tld' => 'The Name']); 501 502 If you want to include multiple addresses then you must use an array:: 503 504 $message->setTo(['some@address.tld', 'other@address.tld']); 505 506 You can mix personalized (addresses with a name) and non-personalized 507 addresses in the same list by mixing the use of associative and 508 non-associative array syntax:: 509 510 $message->setTo([ 511 'recipient-with-name@example.org' => 'Recipient Name One', 512 'no-name@example.org', // Note that this is not a key-value pair 513 'named-recipient@example.org' => 'Recipient Name Two' 514 ]); 515 516 Setting ``To:`` Recipients 517 ~~~~~~~~~~~~~~~~~~~~~~~~~~ 518 519 ``To:`` recipients are required in a message and are set with the ``setTo()`` 520 or ``addTo()`` methods of the message. 521 522 To set ``To:`` recipients, create the message object using either ``new 523 Swift_Message( ... )`` or ``new Swift_Message( ... )``, then call the 524 ``setTo()`` method with a complete array of addresses, or use the ``addTo()`` 525 method to iteratively add recipients. 526 527 The ``setTo()`` method accepts input in various formats as described earlier in 528 this chapter. The ``addTo()`` method takes either one or two parameters. The 529 first being the email address and the second optional parameter being the name 530 of the recipient. 531 532 ``To:`` recipients are visible in the message headers and will be seen by the 533 other recipients:: 534 535 // Using setTo() to set all recipients in one go 536 $message->setTo([ 537 'person1@example.org', 538 'person2@otherdomain.org' => 'Person 2 Name', 539 'person3@example.org', 540 'person4@example.org', 541 'person5@example.org' => 'Person 5 Name' 542 ]); 543 544 .. note:: 545 546 Multiple calls to ``setTo()`` will not add new recipients -- each 547 call overrides the previous calls. If you want to iteratively add 548 recipients, use the ``addTo()`` method:: 549 550 // Using addTo() to add recipients iteratively 551 $message->addTo('person1@example.org'); 552 $message->addTo('person2@example.org', 'Person 2 Name'); 553 554 Setting ``Cc:`` Recipients 555 ~~~~~~~~~~~~~~~~~~~~~~~~~~ 556 557 ``Cc:`` recipients are set with the ``setCc()`` or ``addCc()`` methods of the 558 message. 559 560 To set ``Cc:`` recipients, create the message object using either ``new 561 Swift_Message( ... )`` or ``new Swift_Message( ... )``, then call the 562 ``setCc()`` method with a complete array of addresses, or use the ``addCc()`` 563 method to iteratively add recipients. 564 565 The ``setCc()`` method accepts input in various formats as described earlier in 566 this chapter. The ``addCc()`` method takes either one or two parameters. The 567 first being the email address and the second optional parameter being the name 568 of the recipient. 569 570 ``Cc:`` recipients are visible in the message headers and will be seen by the 571 other recipients:: 572 573 // Using setTo() to set all recipients in one go 574 $message->setTo([ 575 'person1@example.org', 576 'person2@otherdomain.org' => 'Person 2 Name', 577 'person3@example.org', 578 'person4@example.org', 579 'person5@example.org' => 'Person 5 Name' 580 ]); 581 582 .. note:: 583 584 Multiple calls to ``setCc()`` will not add new recipients -- each call 585 overrides the previous calls. If you want to iteratively add Cc: 586 recipients, use the ``addCc()`` method:: 587 588 // Using addCc() to add recipients iteratively 589 $message->addCc('person1@example.org'); 590 $message->addCc('person2@example.org', 'Person 2 Name'); 591 592 Setting ``Bcc:`` Recipients 593 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 594 595 ``Bcc:`` recipients receive a copy of the message without anybody else knowing 596 it, and are set with the ``setBcc()`` or ``addBcc()`` methods of the message. 597 598 To set ``Bcc:`` recipients, create the message object using either ``new 599 Swift_Message( ... )`` or ``new Swift_Message( ... )``, then call the 600 ``setBcc()`` method with a complete array of addresses, or use the ``addBcc()`` 601 method to iteratively add recipients. 602 603 The ``setBcc()`` method accepts input in various formats as described earlier 604 in this chapter. The ``addBcc()`` method takes either one or two parameters. 605 The first being the email address and the second optional parameter being the 606 name of the recipient. 607 608 Only the individual ``Bcc:`` recipient will see their address in the message 609 headers. Other recipients (including other ``Bcc:`` recipients) will not see 610 the address:: 611 612 // Using setBcc() to set all recipients in one go 613 $message->setBcc([ 614 'person1@example.org', 615 'person2@otherdomain.org' => 'Person 2 Name', 616 'person3@example.org', 617 'person4@example.org', 618 'person5@example.org' => 'Person 5 Name' 619 ]); 620 621 .. note:: 622 623 Multiple calls to ``setBcc()`` will not add new recipients -- each call 624 overrides the previous calls. If you want to iteratively add Bcc: 625 recipients, use the ``addBcc()`` method:: 626 627 // Using addBcc() to add recipients iteratively 628 $message->addBcc('person1@example.org'); 629 $message->addBcc('person2@example.org', 'Person 2 Name'); 630 631 .. sidebar:: Internationalized Email Addresses 632 633 Traditionally only ASCII characters have been allowed in email addresses. 634 With the introduction of internationalized domain names (IDNs), non-ASCII 635 characters may appear in the domain name. By default, Swiftmailer encodes 636 such domain names in Punycode (e.g. xn--xample-ova.invalid). This is 637 compatible with all mail servers. 638 639 RFC 6531 introduced an SMTP extension, SMTPUTF8, that allows non-ASCII 640 characters in email addresses on both sides of the @ sign. To send to such 641 addresses, your outbound SMTP server must support the SMTPUTF8 extension. 642 You should use the ``Swift_AddressEncoder_Utf8AddressEncoder`` address 643 encoder and enable the ``Swift_Transport_Esmtp_SmtpUtf8Handler`` SMTP 644 extension handler:: 645 646 $smtpUtf8 = new Swift_Transport_Esmtp_SmtpUtf8Handler(); 647 $transport->setExtensionHandlers([$smtpUtf8]); 648 $utf8Encoder = new Swift_AddressEncoder_Utf8AddressEncoder(); 649 $transport->setAddressEncoder($utf8Encoder); 650 651 Specifying Sender Details 652 ------------------------- 653 654 An email must include information about who sent it. Usually this is managed by 655 the ``From:`` address, however there are other options. 656 657 The sender information is contained in three possible places: 658 659 * ``From:`` -- the address(es) of who wrote the message (required) 660 661 * ``Sender:`` -- the address of the single person who sent the message 662 (optional) 663 664 * ``Return-Path:`` -- the address where bounces should go to (optional) 665 666 You must always include a ``From:`` address by using ``setFrom()`` on the 667 message. Swift Mailer will use this as the default ``Return-Path:`` unless 668 otherwise specified. 669 670 The ``Sender:`` address exists because the person who actually sent the email 671 may not be the person who wrote the email. It has a higher precedence than the 672 ``From:`` address and will be used as the ``Return-Path:`` unless otherwise 673 specified. 674 675 Setting the ``From:`` Address 676 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 677 678 A ``From:`` address is required and is set with the ``setFrom()`` method of the 679 message. ``From:`` addresses specify who actually wrote the email, and usually 680 who sent it. 681 682 What most people probably don't realize is that you can have more than one 683 ``From:`` address if more than one person wrote the email -- for example if an 684 email was put together by a committee. 685 686 The ``From:`` address(es) are visible in the message headers and will be seen 687 by the recipients. 688 689 .. note:: 690 691 If you set multiple ``From:`` addresses then you absolutely must set a 692 ``Sender:`` address to indicate who physically sent the message. 693 694 :: 695 696 // Set a single From: address 697 $message->setFrom('your@address.tld'); 698 699 // Set a From: address including a name 700 $message->setFrom(['your@address.tld' => 'Your Name']); 701 702 // Set multiple From: addresses if multiple people wrote the email 703 $message->setFrom([ 704 'person1@example.org' => 'Sender One', 705 'person2@example.org' => 'Sender Two' 706 ]); 707 708 Setting the ``Sender:`` Address 709 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 710 711 A ``Sender:`` address specifies who sent the message and is set with the 712 ``setSender()`` method of the message. 713 714 The ``Sender:`` address is visible in the message headers and will be seen by 715 the recipients. 716 717 This address will be used as the ``Return-Path:`` unless otherwise specified. 718 719 .. note:: 720 721 If you set multiple ``From:`` addresses then you absolutely must set a 722 ``Sender:`` address to indicate who physically sent the message. 723 724 You must not set more than one sender address on a message because it's not 725 possible for more than one person to send a single message:: 726 727 $message->setSender('your@address.tld'); 728 729 Setting the ``Return-Path:`` (Bounce) Address 730 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 731 732 The ``Return-Path:`` address specifies where bounce notifications should be 733 sent and is set with the ``setReturnPath()`` method of the message. 734 735 You can only have one ``Return-Path:`` and it must not include a personal name. 736 737 Bounce notifications will be sent to this address:: 738 739 $message->setReturnPath('bounces@address.tld'); 740 741 Signed/Encrypted Message 742 ------------------------ 743 744 To increase the integrity/security of a message it is possible to sign and/or 745 encrypt an message using one or multiple signers. 746 747 S/MIME 748 ~~~~~~ 749 750 S/MIME can sign and/or encrypt a message using the OpenSSL extension. 751 752 When signing a message, the signer creates a signature of the entire content of 753 the message (including attachments). 754 755 The certificate and private key must be PEM encoded, and can be either created 756 using for example OpenSSL or obtained at an official Certificate Authority (CA). 757 758 **The recipient must have the CA certificate in the list of trusted issuers in 759 order to verify the signature.** 760 761 **Make sure the certificate supports emailProtection.** 762 763 When using OpenSSL this can done by the including the *-addtrust 764 emailProtection* parameter when creating the certificate:: 765 766 $message = new Swift_Message(); 767 768 $smimeSigner = new Swift_Signers_SMimeSigner(); 769 $smimeSigner->setSignCertificate('/path/to/certificate.pem', '/path/to/private-key.pem'); 770 $message->attachSigner($smimeSigner); 771 772 When the private key is secured using a passphrase use the following instead:: 773 774 $message = new Swift_Message(); 775 776 $smimeSigner = new Swift_Signers_SMimeSigner(); 777 $smimeSigner->setSignCertificate('/path/to/certificate.pem', ['/path/to/private-key.pem', 'passphrase']); 778 $message->attachSigner($smimeSigner); 779 780 By default the signature is added as attachment, making the message still 781 readable for mailing agents not supporting signed messages. 782 783 Storing the message as binary is also possible but not recommended:: 784 785 $smimeSigner->setSignCertificate('/path/to/certificate.pem', '/path/to/private-key.pem', PKCS7_BINARY); 786 787 When encrypting the message (also known as enveloping), the entire message 788 (including attachments) is encrypted using a certificate, and the recipient can 789 then decrypt the message using corresponding private key. 790 791 Encrypting ensures nobody can read the contents of the message without the 792 private key. 793 794 Normally the recipient provides a certificate for encrypting and keeping the 795 decryption key private. 796 797 Using both signing and encrypting is also possible:: 798 799 $message = new Swift_Message(); 800 801 $smimeSigner = new Swift_Signers_SMimeSigner(); 802 $smimeSigner->setSignCertificate('/path/to/sign-certificate.pem', '/path/to/private-key.pem'); 803 $smimeSigner->setEncryptCertificate('/path/to/encrypt-certificate.pem'); 804 $message->attachSigner($smimeSigner); 805 806 The used encryption cipher can be set as the second parameter of 807 setEncryptCertificate() 808 809 See https://secure.php.net/manual/openssl.ciphers for a list of supported ciphers. 810 811 By default the message is first signed and then encrypted, this can be changed 812 by adding:: 813 814 $smimeSigner->setSignThenEncrypt(false); 815 816 **Changing this is not recommended as most mail agents don't support this 817 none-standard way.** 818 819 Only when having trouble with sign then encrypt method, this should be changed. 820 821 Requesting a Read Receipt 822 ------------------------- 823 824 It is possible to request a read-receipt to be sent to an address when the 825 email is opened. To request a read receipt set the address with 826 ``setReadReceiptTo()``: 827 828 $message->setReadReceiptTo('your@address.tld'); 829 830 When the email is opened, if the mail client supports it a notification will be 831 sent to this address. 832 833 .. note:: 834 835 Read receipts won't work for the majority of recipients since many mail 836 clients auto-disable them. Those clients that will send a read receipt 837 will make the user aware that one has been requested. 838 839 Setting the Character Set 840 ------------------------- 841 842 The character set of the message (and its MIME parts) is set with the 843 ``setCharset()`` method. You can also change the global default of UTF-8 by 844 working with the ``Swift_Preferences`` class. 845 846 Swift Mailer will default to the UTF-8 character set unless otherwise 847 overridden. UTF-8 will work in most instances since it includes all of the 848 standard US keyboard characters in addition to most international characters. 849 850 It is absolutely vital however that you know what character set your message 851 (or it's MIME parts) are written in otherwise your message may be received 852 completely garbled. 853 854 There are two places in Swift Mailer where you can change the character set: 855 856 * In the ``Swift_Preferences`` class 857 858 * On each individual message and/or MIME part 859 860 To set the character set of your Message: 861 862 * Change the global UTF-8 setting by calling 863 ``Swift_Preferences::setCharset()``; or 864 865 * Call the ``setCharset()`` method on the message or the MIME part:: 866 867 // Approach 1: Change the global setting (suggested) 868 Swift_Preferences::getInstance()->setCharset('iso-8859-2'); 869 870 // Approach 2: Call the setCharset() method of the message 871 $message = (new Swift_Message()) 872 ->setCharset('iso-8859-2'); 873 874 // Approach 3: Specify the charset when setting the body 875 $message->setBody('My body', 'text/html', 'iso-8859-2'); 876 877 // Approach 4: Specify the charset for each part added 878 $message->addPart('My part', 'text/plain', 'iso-8859-2'); 879 880 Setting the Encoding 881 -------------------- 882 883 The body of each MIME part needs to be encoded. Binary attachments are encoded 884 in base64 using the ``Swift_Mime_ContentEncoder_Base64ContentEncoder``. Text 885 parts are traditionally encoded in quoted-printable using 886 ``Swift_Mime_ContentEncoder_QpContentEncoder`` or 887 ``Swift_Mime_ContentEncoder_NativeQpContentEncoder``. 888 889 The encoder of the message or MIME part is set with the ``setEncoder()`` method. 890 891 Quoted-printable is the safe choice, because it converts 8-bit text as 7-bit. 892 Most modern SMTP servers support 8-bit text. This is advertised via the 8BITMIME 893 SMTP extension. If your outbound SMTP server supports this SMTP extension, and 894 it supports downgrading the message (e.g converting to quoted-printable on the 895 fly) when delivering to a downstream server that does not support the extension, 896 you may wish to use ``Swift_Mime_ContentEncoder_PlainContentEncoder`` in 897 ``8bit`` mode instead. This has the advantage that the source data is slightly 898 more readable and compact, especially for non-Western languages. 899 900 $eightBitMime = new Swift_Transport_Esmtp_EightBitMimeHandler(); 901 $transport->setExtensionHandlers([$eightBitMime]); 902 $plainEncoder = new Swift_Mime_ContentEncoder_PlainContentEncoder('8bit'); 903 $message->setEncoder($plainEncoder); 904 905 Setting the Line Length 906 ----------------------- 907 908 The length of lines in a message can be changed by using the 909 ``setMaxLineLength()`` method on the message:: 910 911 $message->setMaxLineLength(1000); 912 913 Swift Mailer defaults to using 78 characters per line in a message. This is 914 done for historical reasons and so that the message can be easily viewed in 915 plain-text terminals 916 917 Lines that are longer than the line length specified will be wrapped between 918 words. 919 920 .. note:: 921 922 You should never set a maximum length longer than 1000 characters 923 according to RFC 2822. Doing so could have unspecified side-effects such 924 as truncating parts of your message when it is transported between SMTP 925 servers. 926 927 Setting the Message Priority 928 ---------------------------- 929 930 You can change the priority of the message with ``setPriority()``. Setting the 931 priority will not change the way your email is sent -- it is purely an 932 indicative setting for the recipient:: 933 934 // Indicate "High" priority 935 $message->setPriority(2); 936 937 The priority of a message is an indication to the recipient what significance 938 it has. Swift Mailer allows you to set the priority by calling the 939 ``setPriority`` method. This method takes an integer value between 1 and 5: 940 941 * ``Swift_Mime_SimpleMessage::PRIORITY_HIGHEST``: 1 942 * ``Swift_Mime_SimpleMessage::PRIORITY_HIGH``: 2 943 * ``Swift_Mime_SimpleMessage::PRIORITY_NORMAL``: 3 944 * ``Swift_Mime_SimpleMessage::PRIORITY_LOW``: 4 945 * ``Swift_Mime_SimpleMessage::PRIORITY_LOWEST``: 5 946 947 :: 948 949 // Or use the constant to be more explicit 950 $message->setPriority(Swift_Mime_SimpleMessage::PRIORITY_HIGH);
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Tue May 19 15:55:14 2020 | Cross-referenced by PHPXref 0.7.1 |