1. Giới thiệu
Như các bạn đã biết, với đa số các ứng dụng thì việc gửi mail là một chức năng dường như không thể thiếu trong hàng tá các chức năng mà ứng dụng cần phải có. Hôm nay mình sẽ viết một bài hướng dẫn về cách gửi mail với Laravel 5.x.
Laravel sử dụng bộ thư viện SwiftMailer giàu tính năng và hoàn toàn miễn phí để gửi mail. Trước đây để gửi mail việc lựa chọn thư viện và config khá phức tạp, nhưng với bộ thư viện này trong Laravel, chúng ta có thể dễ dàng gửi mail mà không gặp quá nhiều rắc rối. SwiftMailer cung cấp các driver phổ biết như SMTP, Mailgun, SpartPost,…sẽ giúp chúng ta triển khai tính năng gửi mail đơn giản và dễ dàng hơn rất nhiều.
2. Cài đặt package
Tất cả các API drivers đề yêu cầu thư viện Guzzle HTTP, bạn có thể được cài đặt thông qua trình quản lý package Composer với lệnh sau đây:
1 2 | composer require guzzlehttp/guzzle |
3. Config file các biến môi trường của mail trong file .env
1 2 3 4 5 6 7 | MAIL_DRIVER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=587 <a href="/cdn-cgi/l/email-protection" class="__cf_email__">[email protected]</a> MAIL_PASSWORD=********* MAIL_ENCRYPTION=tls |
Mình giải thích một tí nhé
Phương thức gửi mail ở đây là SMTP, host của gmail là smtp.gmail.com, port là 587, MAIL_USERNAME là gmail của bạn và MAIL_PASSWORD chính là mật khẩu của bạn. Ở đây chúng ta cần lưu ý một vài điều sau đây:
Nếu gmail của bạn đang bật bảo mật 2 lớp thì sẽ không thể đăng nhập để gửi mail bằng password gmail như bình thường bạn vẫn dùng để login đâu nhé, lúc này bạn cần phải tạo mật khẩu ứng dụng cho gmail và lấy mật khậu đó điền vào key MAILPASSWORD. Có thể xem hướng dẫn cách tạo mật khẩu ứng dụng cho gmail tại đây
Hoặc nếu không thích dùng file .env thì chúng ta có thể config trong config/mail.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | <?php return [ /* |-------------------------------------------------------------------------- | Mail Driver |-------------------------------------------------------------------------- | | Laravel supports both SMTP and PHP's "mail" function as drivers for the | sending of e-mail. You may specify which one you're using throughout | your application here. By default, Laravel is setup for SMTP mail. | | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses", | "sparkpost", "log", "array" | */ 'driver' => env('MAIL_DRIVER', 'smtp'), /* |-------------------------------------------------------------------------- | SMTP Host Address |-------------------------------------------------------------------------- | | Here you may provide the host address of the SMTP server used by your | applications. A default option is provided that is compatible with | the Mailgun mail service which will provide reliable deliveries. | */ 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), /* |-------------------------------------------------------------------------- | SMTP Host Port |-------------------------------------------------------------------------- | | This is the SMTP port used by your application to deliver e-mails to | users of the application. Like the host we have set this value to | stay compatible with the Mailgun e-mail application by default. | */ 'port' => env('MAIL_PORT', 587), /* |-------------------------------------------------------------------------- | Global "From" Address |-------------------------------------------------------------------------- | | You may wish for all e-mails sent by your application to be sent from | the same address. Here, you may specify a name and address that is | used globally for all e-mails that are sent by your application. | */ 'from' => [ 'address' => env('MAIL_FROM_ADDRESS', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__">[email protected]</a>'), 'name' => env('MAIL_FROM_NAME', 'Example'), ], /* |-------------------------------------------------------------------------- | E-Mail Encryption Protocol |-------------------------------------------------------------------------- | | Here you may specify the encryption protocol that should be used when | the application send e-mail messages. A sensible default using the | transport layer security protocol should provide great security. | */ 'encryption' => env('MAIL_ENCRYPTION', 'tls'), /* |-------------------------------------------------------------------------- | SMTP Server Username |-------------------------------------------------------------------------- | | If your SMTP server requires a username for authentication, you should | set it here. This will get used to authenticate with your server on | connection. You may also set the "password" value below this one. | */ 'username' => env('MAIL_USERNAME'), 'password' => env('MAIL_PASSWORD'), /* |-------------------------------------------------------------------------- | Sendmail System Path |-------------------------------------------------------------------------- | | When using the "sendmail" driver to send e-mails, we will need to know | the path to where Sendmail lives on this server. A default path has | been provided here, which will work well on most of your systems. | */ 'sendmail' => '/usr/sbin/sendmail -bs', /* |-------------------------------------------------------------------------- | Markdown Mail Settings |-------------------------------------------------------------------------- | | If you are using Markdown based email rendering, you may configure your | theme and component paths here, allowing you to customize the design | of the emails. Or, you may simply stick with the Laravel defaults! | */ 'markdown' => [ 'theme' => 'default', 'paths' => [ resource_path('views/vendor/mail'), ], ], /* |-------------------------------------------------------------------------- | Log Channel |-------------------------------------------------------------------------- | | If you are using the "log" driver, you may specify the logging channel | if you prefer to keep mail messages separate from other log entries | for simpler reading. Otherwise, the default channel will be used. | */ 'log_channel' => env('MAIL_LOG_CHANNEL'), ]; |
Lúc này chúng ta có thể bỏ trống các key config mail ở file .env vì nếu có trong file .env thì giá trị sẽ được lấy từ file .env ra mà thôi, tiếp theo ở đây chúng ta tìm các key tương ứng với các key trong file .env và sửa lại cho đúng ý mình nhé, nếu không nó sẽ sử dụng các giá trị mặc định.
4. Test chức năng gửi mail
Ở đây chúng ta sẽ test chức năng gửi mail theo cách đơn giản nhất, chưa nói đến việc tạo class mailable, chúng ta sẽ chỉ test chứng năng gửi mail qua việc xử lý trong một controller.
Tạo một file controller
1 2 | php artisan make:controller MailController --plain |
Copy đoạn code sau vào file MailController.php vừa tạo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <?php namespace AppHttpControllers; use IlluminateHttpRequest; use Mail; use AppHttpRequests; use AppHttpControllersController; class MailController extends Controller { public function basic_email() { $data = array('name'=>"Virat Gandhi"); Mail::send(['text'=>'mail'], $data, function($message) { $message->to('<a href="/cdn-cgi/l/email-protection" class="__cf_email__">[email protected]</a>', 'Tutorials Point')->subject ('Laravel Basic Testing Mail'); $message->from('<a href="/cdn-cgi/l/email-protection" class="__cf_email__">[email protected]</a>','Virat Gandhi'); }); echo "Basic Email Sent. Check your inbox."; } public function html_email() { $data = array('name'=>"Virat Gandhi"); Mail::send('mail', $data, function($message) { $message->to('<a href="/cdn-cgi/l/email-protection" class="__cf_email__">[email protected]</a>', 'Tutorials Point')->subject ('Laravel HTML Testing Mail'); $message->from('<a href="/cdn-cgi/l/email-protection" class="__cf_email__">[email protected]</a>','Virat Gandhi'); }); echo "HTML Email Sent. Check your inbox."; } public function attachment_email() { $data = array('name'=>"Virat Gandhi"); Mail::send('mail', $data, function($message) { $message->to('<a href="/cdn-cgi/l/email-protection" class="__cf_email__">[email protected]</a>', 'Tutorials Point')->subject ('Laravel Testing Mail with Attachment'); $message->attach('path/to/attachment.txt'); $message->attach('path/to/image.png'); $message->from('<a href="/cdn-cgi/l/email-protection" class="__cf_email__">[email protected]</a>','Virat Gandhi'); }); echo "Email Sent with attachment. Check your inbox."; } } |
Tạo một file template để test view của mail
resources/views/mail.blade.php
Copy đoạn code dưới vào file template vừa tạo
1 2 3 | <h1>Hi, {{ $name }}</h1> <p>Sending Mail from Laravel.</p> |
Tạo route
app/Http/routers.php
Copy đoạn code sau vào file route
1 2 3 4 | Route::get('sendbasicemail','<a href="/cdn-cgi/l/email-protection" class="__cf_email__">[email protected]</a>_email'); Route::get('sendhtmlemail','<a href="/cdn-cgi/l/email-protection" class="__cf_email__">[email protected]</a>_email'); Route::get('sendattachmentemail','<a href="/cdn-cgi/l/email-protection" class="__cf_email__">[email protected]</a>_email'); |
Sau đó truy cập vào url sau để kiểm tra email cơ bản
1 2 | http://localhost:8000/sendbasicemail |
và màn hình đầu ra sẽ trông giống như thế này
Tiếp theo, truy cập vào url http://localhost:8000/sendhtmlemail
để check email với html
1 2 | http://localhost:8000/sendhtmlemail |
Màn hình đầu ra của html
Và sau cùng truy cập vào url sau http://localhost:8000/sendattachmentemail
để kiểm tra email có tệp đính kèm. Chúng ta sẽ thấy có màn hình sau:
5. Kết thúc
Như vậy về cơ bản chúng ta đã nắm được cáhc config và điều kiện để gửi mail theo cách cơ bản nhất. Bài viết lần này còn là hướng dẫn khá cơ bản và chắc chắn có những thiếu sót mong các bạn góp ý và bỏ qua cho mình nhé
Nguồn tham khảo:
https://laravel.com/docs/5.7/mail
https://www.tutorialspoint.com/laravel/laravel_sending_email.htm