Laravel 5.1 uses SMTP to send emails (including attachments and images).

Source: Internet
Author: User
Tags closure php and email account

1. Configuration file
Laravel integrates the SwiftMailer library for mail sending. The mail configuration file is in config/mail. php:

Return [
'Driver '=> env ('mail _ driver', 'smtp '),
'Host' => env ('mail _ host', 'smtp .mailgun.org '),
'Port' => env ('mail _ port', 587 ),
'From' => ['address' => null, 'name' => null],
'Encryption' => env ('mail _ encryption', 'tls '),
'Username' => env ('mail _ username '),
'Password' => env ('mail _ password '),
'Sendmail' => '/usr/sbin/sendmail-bs ',
'Pretend' => false,
]
The driver is used to configure the default mail sending driver. Laravel supports multiple mail driving methods, including smtp, Mailgun, Maildrill, Amazon SES, mail, sendmail, Mailgun, and Amazon SES, maildrill currently does not support users in China, all of which are third-party email services. The mail driver uses the mail function provided by PHP to send emails. The sendmail driver sends emails through Commands provided by Sendmail/Postfix (Linux). The smtp driver sends emails through SMTP that supports ESMTP.

Note: ESMTP, or Extended SMTP, is an extension of the standard SMTP protocol. The difference between ESMTP and the SMTP service is that when sending mail via SMTP, the user account does not need to be verified, but when sending mail via ESMTP, the server requires the user to provide the user name and password for authentication.
As for the current situation, using smtp is the smartest choice. mail is not secure. To use sendmail, you must install and configure Sendmail/Postfix. Others are either paid or unavailable !). The other configuration instructions below are based on the driver being smtp.

Other configurations are easy to understand. host is the host where the mailbox is located. For example, if we use 163 mailbox, the corresponding value is smtp.163.com. If we use QQ mailbox, the corresponding value is smtp.qq.com.

Port is used to configure the Mail sending service port number. For example, the default value is 25. If SMTP is set to use SSL encryption, the value is 465.

The from configuration item contains the address and name. The former indicates the email sending address, and the latter indicates the user name used to send the email.

Encryption indicates the encryption type. If it is set to null, it means no encryption is used, or it can be set to tls/ssl.

Username indicates the mailbox account, such as the yaojinbu@163.com

Password indicates the logon password of the above email account.

Sendmail is used to specify the sendmail command path when the driver is set to sendmail.

Pretend is used to configure whether to record mail sending to logs. If it is set to false by default, no mail sending logs are recorded. If it is set to true, only logs are recorded and no mail is sent, this configuration is useful in local development debugging.

Enter this configuration file based on your email service and email account. Of course, many configuration values need to be set in. env.

2. Define a route
Define routing rules for our tests in routes. php:

Route: get ('mail/send', 'mailcontroller @ send ');
3. Logic implementation of Mail sending
Create a controller

Next, create a controller that matches the route and use the following command to create a clean MailController:

Php artisan make: controller MailController -- plain
Generate a new controller MailController in the app/Http/Controllers Directory:

<? Php

Namespace App \ Http \ Controllers;

Use Illuminate \ Http \ Request;

Use App \ Http \ Requests;
Use App \ Http \ Controllers \ Controller;

Class MailController extends Controller
{
//
}
Simple email sending implementation

Add the send email action send () to the controller. We use the send method of the Mail facade to send the Mail. We will first send the simplest Mail:

<? Php

Namespace App \ Http \ Controllers;

Use Illuminate \ Http \ Request;

Use App \ Http \ Requests;
Use App \ Http \ Controllers \ Controller;

Use Mail;

Class MailController extends Controller
{
Public function send ()
    {
$ Name = '';
$ Flag = Mail: send ('emails. Test', ['name' => $ name], function ($ message ){
$ To = '2017 @ qq.com ';
$ Message-> to ($ to)-> subject ('test mail ');
});
If ($ flag ){
Echo 'email sent successfully. Please check it! ';
} Else {
Echo 'failed to send the email. Please try again! ';
        }
    }
}
Mail: send requires three parameters. The first is the Mail view, the second is the data passed into the view, and the third is a closure, the closure defines the recipient, CC (if any), email subject, attachment, and other information. The subject content of the email is located in the local view. Next we will define this local View. In the resources/views/emails Directory, create test. blade. php and edit the content as follows:

{$ Name}. This is a test email.
Then we can access the http://laravel.app: 8000/mail/send in the browser to send the mail, if the page shows that the mail is successfully sent, then the recipient mailbox will receive the mail:

Simpler text mail

The above example only sends a string. For plain text string emails, there is a simpler method:

Mail: raw ('This is a test mail', function ($ message ){
$ To = '2017 @ qq.com ';
$ Message-> to ($ to)-> subject ('test mail ');
});
In this way, you can send emails without creating a view.

Send emails with attachments (garbled Chinese characters)

Of course, the Mail content is often not just plain text. Sometimes we add attachments to the Mail. How can this be achieved?

First run the code:

$ Flag = Mail: send ('emails. Test', ['name' => $ name], function ($ message ){
$ To = '2017 @ qq.com ';
$ Message-> to ($ to)-> subject ('test mail ');

$ Attachment = storage_path ('app/files/test.doc ');
// Upload attachments in the email
$ Message-> attach ($ attachment, ['as' => 'test document .doc ']);
});
From the code, we can see that the attach method on the $ message instance in the closure is used to upload attachments. The first parameter of this method is the attachment address, and the second parameter is some additional parameters, here we use as to specify the display name of the attachment in the email.

Note: $ message is actually an instance of Illuminate \ Mail \ Message. We can call all methods of the message class on $ Message.
Access the http://laravel.app again: 8000/mail/send to send the mail, so that you can see the attachment in the inbox, but the attachment name appears Chinese garbled, the solution is as follows:

$ Message-> attach ($ attachment, ['as' => "=? UTF-8? B? ". Base64_encode ('test document ')."? =.Doc "]);
After such processing, there will be no Chinese garbled characters:

Send email with image

Embed

In addition to attachments, sometimes images are inserted into the email content to enrich the Mail content. Although we can hard-code the image path in the mail view, this is obviously cumbersome, poor flexibility. Laravel provides us with a convenient method-use the embed method on $ message in the view:

{$ Name}. This is a test email.
<Br>
embed ($ imgPath) }}">
The $ message here is the $ message in the above mail sending closure. Laravel automatically transmits this variable to the Mail view. Of course, we also need to input the $ imgPath variable in the controller action:

$ Name = '';
$ ImgPath = 'http: // laravelacademy.org/wp-statics/images/carousel/laravelacademy.jpg ';
$ Flag = Mail: send ('emails. Test', ['name' => $ name, 'imgpath' => $ imgPath], function ($ message ){
$ To = '2017 @ qq.com ';
$ Message-> to ($ to)-> subject ('test mail ');

$ Attachment = storage_path ('app/files/test.doc ');
// Upload attachments in the email
$ Message-> attach ($ attachment, ['as' => "=? UTF-8? B? ". Base64_encode ('test document ')."? =.Doc "]);
});
Access http://laravel.app: 8000/mail/send in your browser to send the mail, and check in your inbox after The mail is successfully sent:

Laravel sends an email with an image

Therefore, the image has been inserted into the email content.

In addition, native image data can be sent to emails to read local images to the memory and then rendered to the Mail view. This can be achieved through embedData on $ message.

First, modify the controller as follows:

$ Name = '';
// $ ImgPath = 'http: // laravelacademy.org/wp-statics/images/carousel/laravelacademy.jpg ';
$ Image = Storage: get ('images/test.jpg ');
$ Flag = Mail: send ('emails. Test', ['name' => $ name, 'image' => $ image], function ($ message ){
$ To = '2017 @ qq.com ';
$ Message-> to ($ to)-> subject ('test mail ');

$ Attachment = storage_path ('app/files/test.doc ');
// Upload attachments in the email
$ Message-> attach ($ attachment, ['as' => "=? UTF-8? B? ". Base64_encode ('test document ')."? =.Doc "]);
});
Remember to add use Storage on the top of MailController, and then modify the Mail view test. blade. php as follows:

{$ Name}. This is a test email.
<Br>
embeddata(your image,'laravelacademy.jpg ')}">
Finally go to the browser to access the http://laravel.app: 8000/mail/send mail, mail sent successfully go to the inbox to view the mail content:

You can also insert images.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.