| 語法 | void send(string|array $view, array $data, Closure|string $callback) |
|---|---|
| 參數 |
|
| 返回值 | nothing |
| 描述 | 發送郵件 |
- $message->subject('Welcome to the zaixian zaixian');
- $message->from('email@example.com', 'Mr. Example');
- $message->to('email@example.com', 'Mr. Example');
- $message->sender('email@example.com', 'Mr. Example');
- $message->returnPath('email@example.com');
- $message->cc('email@example.com', 'Mr. Example');
- $message->bcc('email@example.com', 'Mr. Example');
- $message->replyTo('email@example.com', 'Mr. Example');
- $message->priority(2);
- $message->attach('path/to/attachment.txt');
- $message->embed('path/to/attachment.jpg');
郵件可以發送HTML或文本。您可以通過傳遞一個數組指明發送郵件的類型,如下圖所示的第一個參數。默認類型為HTML。如果您想發送純文本郵件,然後使用以下語法。
語法
Mail::send([‘text’=>’text.view’], $data, $callback);
示例
第1步 - 現在要從Gmail帳戶發送電子郵件,那麼這裏需要配置Laravel環境檔中的Gmail帳戶 — .env 檔。Gmail帳戶啟用兩步驗證,創建一個應用程式並指定密碼,如下圖所示修改 .env 中的參數。
.env
MAIL_DRIVER = smtp MAIL_HOST = smtp.qq.com MAIL_PORT = 587 MAIL_USERNAME = QQ郵箱地址,如:2211@qq.com 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'=>"zaixian-User"); Mail::send(['text'=>'mail'], $data, function($message) {
$message->to('xuhuhu.com@gmail.com', 'zaixian zaixian')->subject
('Laravel Basic Testing Mail');
$message->from('xxxxxx@qq.com','zaixian Author');
});
echo "Basic Email Sent. Check your inbox.";
}
public function html_email(){
$data = array('name'=>"zaixian-User"); Mail::send('mail', $data, function($message) {
$message->to('zaixian_com@qq.com', 'zaixian zaixian')->subject
('Laravel HTML Testing Mail');
$message->from('xxxxx@qq.com','zaixian Author');
});
echo "HTML Email Sent. Check your inbox.";
}
public function attachment_email(){
$data = array('name'=>"zaixian-User"); Mail::send('mail', $data, function($message) {
$message->to('xuhuhu.com@gmail.com', 'zaixian zaixian')->subject
('Laravel Testing Mail with Attachment');
$message->attach('D:\laravel\public\uploads\image.png');
$message->attach('D:\laravel\public\uploads\test.txt');
$message->from('xxxx@qq.com','zaixian 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檔中的表單方法的電子郵件地址是用來發送電子郵件的電子郵件地址。一般來說,它應是伺服器上配置的電子郵件地址。
