語法 | void send(string|array $view, array $data, Closure|string $callback) |
---|---|
引數 |
|
返回值 | nothing |
描述 | 傳送郵件 |
郵件可以傳送HTML或文字。您可以通過傳遞一個陣列指明傳送郵件的型別,如下圖所示的第一個引數。預設型別為HTML。如果您想傳送純文字郵件,然後使用以下語法。
Mail::send([‘text’=>’text.view’], $data, $callback);
第1步 - 現在要從Gmail帳戶傳送電子郵件,那麼這裡需要組態Laravel環境檔案中的Gmail帳戶 — .env 檔案。Gmail帳戶啟用兩步驗證,建立一個應用程式並指定密碼,如下圖所示修改 .env 中的引數。
MAIL_DRIVER = smtp MAIL_HOST = smtp.qq.com MAIL_PORT = 587 MAIL_USERNAME = QQ郵箱地址,如:[email protected] MAIL_PASSWORD = QQ密碼 MAIL_ENCRYPTION = tls
php artisan config:cache
php artisan make:controller MailController
第5步 - 複製下面的程式碼到 app/Http/Controllers/MailController.php 檔案,具體程式碼如下:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Mail; use App\Http\Requests; use App\Http\Controllers\Controller; class MailController extends Controller { public function basic_email(){ $data = array('name'=>"Yiibai-User"); Mail::send(['text'=>'mail'], $data, function($message) { $message->to('[email protected]', 'Yiibai Yiibai')->subject ('Laravel Basic Testing Mail'); $message->from('[email protected]','Yiibai Author'); }); echo "Basic Email Sent. Check your inbox."; } public function html_email(){ $data = array('name'=>"Yiibai-User"); Mail::send('mail', $data, function($message) { $message->to('[email protected]', 'Yiibai Yiibai')->subject ('Laravel HTML Testing Mail'); $message->from('[email protected]','Yiibai Author'); }); echo "HTML Email Sent. Check your inbox."; } public function attachment_email(){ $data = array('name'=>"Yiibai-User"); Mail::send('mail', $data, function($message) { $message->to('[email protected]', 'Yiibai Yiibai')->subject ('Laravel Testing Mail with Attachment'); $message->attach('D:\laravel\public\uploads\image.png'); $message->attach('D:\laravel\public\uploads\test.txt'); $message->from('[email protected]','Yiibai Author'); }); echo "Email Sent with attachment. Check your inbox."; } }
resources/views/mail.blade.php
<h1>Hi, {{ $name }}</h1> <p>Sending Mail from Laravel.</p>
app/Http/routes.php
Route::get('sendbasicemail','MailController@basic_email'); Route::get('sendhtmlemail','MailController@html_email'); Route::get('sendattachmentemail','MailController@attachment_email');
http://localhost:8000/sendbasicemail
http://localhost:8000/sendhtmlemail
第11步 - 輸出的畫面將是這個樣子。請檢查您的收件箱是否看到HTML的電子郵件輸出。
http://localhost:8000/sendattachmentemail
註 - 在MailController.php檔案中的表單方法的電子郵件地址是用來傳送電子郵件的電子郵件地址。一般來說,它應是伺服器上組態的電子郵件地址。