Mail – Laravel – The PHP Framework For Web Artisans

  • introduction
    • configuration
    • driver prerequisites
    • failover configuration
    • configure sender
    • configure view
    • view data
    • attachments
    • inline attachments
    • attachable objects
    • tags & metadata
    • customize symfony message
    • generate discount emails
    • write discount messages
    • customize components
    • mail in queue
    • email preview in browser
    • additional symfony transports

    intro

    Sending email doesn’t have to be complicated. Laravel provides a clean and simple email api powered by the popular symfony mail component. laravel and symfony mailer provide drivers for sending email via smtp, mailgun, postmark, amazon ses, and sendmail, allowing you to quickly start sending mail via a local or cloud-based service of your choice.

    settings

    Laravel’s email services can be configured via your application’s config/mail.php configuration file. each mailer configured within this file can have its own unique settings and even its own unique “transport”, allowing your application to use different email services to send certain emails. for example, your application could use postmarks to send transactional emails while using amazon ses to send bulk emails.

    Inside your mail configuration file, you will find an array of mail configuration. this array contains a sample configuration entry for each of the major mail handlers/transports supported by laravel, while the default configuration value determines which mail program will be used by default when your application needs to send a mail message email.

    driver / transportation prerequisites

    Api-based drivers like mailgun and postmark are usually easier and faster than sending mail through smtp servers. Whenever possible, we recommend that you use one of these drivers.

    mail gun driver

    to use the mailgun driver, install the symfony mailgun mail transport via composer:

    then set the default option in your application’s config/mail.php configuration file to mailgun. After setting your application’s default mail, check that your config/services.php configuration file contains the following options:

    If you are not using the US mailgun region, you can define your region endpoint in the services configuration file:

    postmark handler

    To use the postmark driver, install the symfony postmark mail transport via composer:

    then set the default option in your application’s config/mail.php configuration file to postmark. After setting your application’s default mail, check that your config/services.php configuration file contains the following options:

    If you want to specify which postmarked message stream a particular sender should use, you can add the message_stream_id configuration option to the sender configuration array. this configuration array can be found in your application’s config/mail.php configuration file:

    This way you can also set up multiple mailings with different message flows.

    ses controller

    To use the amazon ses driver, you must first install the amazon aws sdk for php. you can install this library via composer package manager:

    Next, set the default option in your config/mail.php configuration file to ses and verify that your config/services.php configuration file contains the following options:

    To use temporary aws credentials via a session token, you can add a token key to your application’s ses configuration:

    if you want to define additional options that laravel should pass to the aws sdk’s sendemail method when sending an email, you can define an array of options within your ses configuration:

    failover configuration

    Sometimes an external service that you have configured to send your application’s mail may be down. In these cases, it may be useful to define one or more backup mail delivery configurations to be used in case your primary delivery controller fails.

    To accomplish this, you must define a mail program within your application’s mail configuration file that uses the failover transport. The configuration array for your application’s failover mail should contain an array of mails that reference the order in which mail handlers should be chosen for delivery:

    once your failover mail has been defined, you need to set this mail as the default mail used by your application by specifying its name as the value of the default configuration key within your application’s mail configuration file :

    generating emails

    when creating laravel applications, each type of email sent by your application is represented as a “mailable” class. these classes are stored in the app/mail directory. don’t worry if you don’t see this directory in your application, as it will be generated when you create your first mailable class using the command make:mail artisan:

    write emails

    Once you’ve generated a mailable class, open it so we can explore its contents. First, note that all configuration for a mailable class is done in the compile method. Within this method, you can call various methods such as from, subject, view, and attach to configure the presentation and delivery of the email.

    Note that you can write indirect dependencies on the mail build method. Laravel’s service container automatically injects these dependencies.

    set sender

    using the from method

    First, let’s explore the email sender settings. or, in other words, whose is it going to be “from”. There are two ways to set the sender. First, you can use the from method inside your mailable class’s compile method:

    using a global sender address

    However, if your application uses the same “from” address for all of its emails, it can be tricky to call the from method on each class that generates mail. instead, you can specify a global “from” address in your config/mail.php configuration file. this address will be used if no other “from” address is specified within the mailable class:

    Also, you can define a global “reply_to” address within your config/mail.php configuration file:

    configuring the view

    Inside the compiler method of a mailable class, you can use the view method to specify which template should be used when rendering the email content. Since each email typically uses a blade template to render its content, you have all the power and convenience of the blade template engine when creating your email’s html:

    note you may want to create a resources/views/emails directory to house all your email templates; however, you can place them wherever you like within your resources/views directory.

    plain text emails

    If you want to define a plain text version of your email, you can use the text method. Like the display method, the text method accepts a template name that will be used to render the content of the email. you are free to define an html and plain text version of your message:

    view data

    via public properties

    Usually you’ll want to pass some data to your view that it can use when rendering the html of the email. there are two ways to make the data available for your view. first, any public properties defined in your mailer class will automatically be available to the view. so, for example, you can pass data to your mailable class’s constructor and set that data to public properties defined on the class:

    once the data has been set to a public property, it will automatically be available in your view, so you can access it just like you would access any other data in your sheet templates:

    via the with method:

    If you want to customize the format of your email data before sending it to the template, you can manually pass your data to the view via the with method. usually you’ll still pass data through the constructor of the mailable class; however, you must set this data to protected or private properties so that the data is not automatically available to the template. then, when calling the with method, pass in a string of data that you want to make available to the template:

    once the data has been passed to the with method, it will automatically be available in your view, so you can access it like you would any other data in your sheet templates:

    attachments

    To add attachments to an email, use the connect method within the compile method of the mailable class. the attach method accepts the full path to the file as its first argument:

    When attaching files to a message, you can also specify the display name and/or mime type by passing an array as the second argument to the attach method:

    attach files from disk

    if you have stored a file on one of your file system disks, you can attach it to the email using the attached storage method:

    If necessary, you can specify the file attachment name and additional options using the second and third arguments of the addedfromstorage method:

    the attach from storage disk method can be used if you need to specify a storage disk other than your default disk:

    raw data attachments

    The attachment method can be used to attach a raw byte string as an attachment. for example you can use this method if you have generated a pdf in memory and want to attach it to email without writing it to disk. the attachment method accepts the raw data bytes as the first argument, the file name as the second argument, and an array of options as the third argument:

    inline attachments

    Embedding inline images in your emails is often cumbersome; however, Laravel provides a convenient way to attach images to your emails. To insert an image inline, use the insert method on the $message variable within your email template. Laravel automatically makes the $message variable available to all your email templates, so you don’t need to worry about passing it manually:

    Warning the $message variable is not available in plain text message templates as plain text messages do not use inline attachments.

    embedding raw data attachments

    If you already have a string of raw image data that you want to embed in an email template, you can call the embeddata method on the $message variable. when calling the embeddata method, you will need to provide a file name that should be assigned to the embedded image:

    dockable objects

    Although attaching files to messages via simple string paths is usually sufficient, in many cases attachable entities within your application are represented by classes. for example, if your app attaches a photo to a message, your app can also have a photo model that represents that photo. when that’s the case, wouldn’t it be convenient to just pass the model from the photo to the attach method? dockable objects let you do just that.

    To get started, implement the illuminatecontractsmailattachable interface on the object that will be attached to messages. this interface dictates that your class define a tomailattachment method that returns an instance of illuminatemailattachment:

    once you’ve defined your attachable object, you can simply pass an instance of that object to the attach method when creating an email message:

    of course, attachments can be stored on a remote file storage service like amazon s3. therefore, laravel also allows you to generate attachment instances from data stored on one of your application’s filesystem disks:

    Also, you can instantiate attachments using the data you have in memory. To accomplish this, provide a closure to the fromdata method. the closure should return the raw data that represents the attachment:

    Laravel also provides additional methods that you can use to customize your attachments. for example, you can use the as and withmime methods to customize the file name and mime type:

    tags and metadata tags

    Some third-party email providers, such as mailgun and postmark, support message “tags” and “metadata”, which can be used to group and track emails sent by your application. you can add tags and metadata to an email message via the tags and metadata methods:

    If your application uses the mailgun driver, you can refer to the mailgun documentation for more information on tags and metadata. You can also refer to the postmark documentation for more information on its support for tags and metadata.

    if your app uses amazon ses to send email, you must use the metadata method to attach ses “tags” to the message.

    customize symfony message

    The withsymfonymessage method of the mailable base class allows you to register a closure that will be invoked with the symfony message instance before sending the message. this gives you the opportunity to deeply personalize the message before it is delivered:

    discount postal messages

    markdown emails allow you to take advantage of pre-built email notification templates and components in your emails. Since the posts are written in markdown, Laravel can generate beautiful responsive html templates for the posts while automatically generating a plain text counterpart.

    generate rebate mailings

    To generate a mailing with a corresponding discount template, you can use the -markdown option of the make:mail artisan command:

    then when setting up the mailing within your build method, call the reduce method instead of the display method. the markdown method accepts the name of the markdown template and an optional array of data to make available to the template:

    write discount messages

    markdown mail elements use a combination of blade components and markdown syntax that allow you to easily build mail messages while taking advantage of Laravel’s pre-built email UI components:

    note do not use excessive indentation when writing sales emails. per markdown standards, markdown parsers will render indented content as blocks of code.

    button component

    The button component renders a centered button link. the component accepts two arguments, a url and an optional color. supported colors are primary, correct, and error. you can add as many button components to a message as you like:

    panel component

    The panel component renders the given block of text in a panel that has a slightly different background color than the rest of the message. this allows you to draw attention to a given block of text:

    table component

    The table component allows you to transform a markdown table into an html table. the component accepts the markdown table as its content. table column alignment is supported by the default markdown table alignment syntax:

    component customization

    You can export all markdown mail components to your own application for customization. to export the components, use the vendor:publish craft command to publish the laravel-mail asset tag:

    This command will publish the markdown mail components to the resources/views/provider/mail directory. the mail directory will contain an html and a text directory, each with their respective representations of each available component. you are free to customize these components however you like.

    customizing the css

    After exporting the components, the resources/views/vendor/mail/html/themes directory will contain a default .css file. you can customize the css in this file and your styles will automatically be converted to inline css styles within the html renditions of your sale emails.

    if you want to create a completely new theme for the laravel markdown components, you can put a css file in the html/themes directory. After naming and saving your css file, update the theme option in your application’s config/mail.php configuration file to match the name of your new theme.

    To customize the theme for an individual mailer, you can set the mailer class’s $theme property to the name of the theme to use when sending that mailer.

    sending mail

    To send a message, use the to method on the mail facade. the to method accepts an email address, a user instance, or a collection of users. if you pass an object or a collection of objects, the sender will automatically use its name and email properties when determining email recipients, so make sure these attributes are available on your objects. once you’ve specified your recipients, you can pass an instance of your mail class to the send method:

    You are not limited to specifying “to” recipients when sending a message. you are free to set “to”, “cc”, and “bcc” recipients by chaining their respective methods together:

    walking through the recipients

    From time to time, you may need to send an email to a list of recipients by iterating over a series of recipients/email addresses. however, because the to method adds email addresses to the mailing’s list of recipients, each iteration through the loop will send another email to each previous recipient. therefore, you must always recreate the mailable instance for each recipient:

    send mail through a specific sender

    By default, Laravel will send emails using the mail configured as the default mail in your application’s mail configuration file. however, you can use the mail method to send a message using specific mail settings:

    mail in queue

    queue a mail message

    Because sending email messages can negatively affect the response time of your application, many developers choose to queue email messages to send them in the background. Laravel makes this easy using its built-in Unified Queue API. To queue a mail message, use the queue method on the mail facade after specifying the recipients of the message:

    this method will automatically take care of sending a job to the queue so that the message is sent in the background. you will need to configure your queues before using this feature.

    delayed message queue

    If you want to delay the delivery of a queued email message, you can use the last method. as the first argument, the last method accepts a datetime instance indicating when the message should be sent:

    pushing to specific queues

    Because all mailable classes generated with the make:mail command use the illuminatebusqueueable trait, you can call the onqueue and onconnection methods on any mailable class instance, which allows you to specify the connection and queue name for the message:

    enqueue by default

    If you have mailable classes and you want them to always be queued, you can implement the shouldqueue contract on the class. now, even if you call the send method when you send mail, the send will still be queued since it implements the contract:

    queued mail messages & database transactions

    When queued mail items are sent within database transactions, they may be processed by the queue before the database transaction is committed. when this happens, any updates you have made to the database models or records during the database transaction may not yet be reflected in the database. additionally, any models or database records created within the transaction may not exist in the database. if your mailer depends on these models, unexpected errors can occur when the job that sends the queued mailer is processed.

    if your queue connection’s after_commit configuration option is set to false, you can still indicate that a particular queued mail should be sent after all open database transactions have been committed by calling the aftercommit method when sending the email:

    Alternatively, you can call the aftercommit method from your mail’s constructor:

    note for more information on how to troubleshoot these issues, see the documentation on queue jobs and database transactions.

    mail rendering

    sometimes you may want to capture the html content of a mailing without sending it. to accomplish this, you can call the render method of mail. this method will return the evaluated html content of the mail as a string:

    mail preview in browser

    When designing a mailing template, it’s a good idea to quickly preview the rendered mailing in your browser as a typical sheet template. for this reason, laravel allows you to return any mail directly from a route closure or controller. when a mailing is returned, it is rendered and displayed in the browser, allowing you to quickly preview your design without sending it to an actual email address:

    Warning Inline attachments will not be processed when previewing an email submission in your browser. To preview these emails, you need to send them to an email testing application like mailhog or helo.

    location of mail elements

    laravel allows you to send mail items in a locale other than the request’s current locale, and will even remember this locale if mail is queued.

    To achieve this, the mail facade offers a local method to set the desired language. the app will switch to this locale when the mailing template is evaluated, and then revert back to the previous locale when the evaluation is complete:

    user preferred locales

    Sometimes applications store each user’s preferred locale. By implementing the haslocalepreference contract in one or more of your models, you can tell Laravel to use this stored locale when sending mail:

    once you have implemented the interface, laravel will automatically use the preferred locale when sending emails and notifications to the model. therefore, there is no need to call the locale method when using this interface:

    testing mail delivery

    laravel provides several convenient methods to test that your emails contain the content you expect. these methods are: assert view in html, assert view not in html, assert view in order in html, assert view in text, assert view not in text, and assert view in order in text.

    Unsurprisingly, “html” assertions assert that the html version of your mail contains a given string, while “text” assertions assert that the plain text version of your mail contains a given string:

    testing mail delivery

    We suggest testing the content of your mailings separately from evidence that a given mailing was “delivered” to a specific user. To learn how to prove that emails were sent, see our documentation on spoofed email.

    mail & local development

    When developing an application that sends email, you probably don’t want to send email to active email addresses. Laravel provides several ways to “disable” the actual sending of emails during local development.

    log handler

    Instead of sending your emails, the log mail handler will write all email messages to your log files for inspection. normally this driver would only be used during local development. For more information on how to configure your application per environment, see the configuration documentation.

    helo / mailtrap / mailhog

    Alternatively, you can use a service like helo or mailtrap and the smtp handler to send your emails to a “dummy” mailbox where you can view them in a real email client. this approach has the advantage of allowing you to inspect the final emails in mailtrap’s message viewer.

    if you are using laravel sail, you can preview your messages using mailhog. when sail is running, you can access the mailhog interface at: http://localhost:8025.

    using a global address

    Finally, you can specify a global “to” address by invoking the alwaysto method offered by the mail facade. Typically, this method should be called from the startup method of one of your application’s service providers:

    events

    laravel fires two events during the process of sending mail messages. the message send event fires before a message is sent, while the message send event fires after a message has been sent. remember, these events are fired when mail is sent, not when it is queued. you can register event listeners for this event in your service provider appproviderseventserviceprovider:

    custom transports

    laravel includes a variety of mail transports; however, you may want to write your own transports to send email through other services that Laravel doesn’t support out of the box. To start with, define a class that extends the symfonycomponentmailertransportabstracttransport class. then implement the dosend and __tostring() methods in your transport:

    once you have defined your custom transport, you can register it via the extended method provided by the mail facade. Typically, this should be done within your application’s appserviceprovider service provider startup method. a $config argument will be passed to the closure provided to the extend method. this argument will contain the configuration array defined for mail in the application’s config/mail.php configuration file:

    Once your custom transport has been defined and registered, you can create a mail definition within your application’s config/mail.php configuration file that uses the new transport:

    additional symfony transports

    laravel includes support for some existing mail transports maintained by symfony like mailgun and postmark. however, you may wish to extend laravel with support for additional transports maintained by symfony. you can do this by requesting the necessary symfony mail via composer and registering the transport with laravel. for example, you can install and register the symfony mail program “sendinblue”:

    once the sendinblue mail package has been installed, you can add an entry for your sendinblue api credentials to your application’s services configuration file:

    finally, you can use the mail facade extension method to register the transport with laravel. Typically, this should be done within a service provider’s startup method:

    See Also:  Cách truy cập gmail bằng mozilla thunderbird

Leave a Reply

Your email address will not be published. Required fields are marked *