前置作業
首先在 Mailgun 服務註冊一個帳號,並且把要接收的電子郵件地址添加到「Authorized Recipients」列表中。
建立專案
建立專案。
| 12
 
 | laravel new examplecd example
 
 | 
修改 .env 檔。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | MAIL_MAILER=mailgunMAIL_HOST=smtp.mailgun.org
 MAIL_PORT=587
 MAIL_USERNAME=your-mail-username
 MAIL_PASSWORD=your-mail-password
 MAIL_ENCRYPTION=tls
 MAIL_FROM_ADDRESS="[email protected]"
 MAIL_FROM_NAME="${APP_NAME}"
 
 MAILGUN_DOMAIN=your-mailgun-domain
 MAILGUN_SECRET=your-mailgun-secret
 
 | 
安裝套件
安裝套件。
| 1
 | composer require symfony/mailgun-mailer symfony/http-client
 | 
建立郵件類別
建立一個 HelloEmail 郵件類別。
| 1
 | php artisan make:mail HelloEmail
 | 
修改 HelloEmail.php 檔。
| 12
 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
 
 | <?php
 namespace App\Mail;
 
 use Illuminate\Bus\Queueable;
 use Illuminate\Contracts\Queue\ShouldQueue;
 use Illuminate\Mail\Mailable;
 use Illuminate\Mail\Mailables\Content;
 use Illuminate\Mail\Mailables\Envelope;
 use Illuminate\Queue\SerializesModels;
 
 class HelloEmail extends Mailable
 {
 use Queueable, SerializesModels;
 
 
 
 
 
 
 public function __construct()
 {
 
 }
 
 
 
 
 
 
 public function envelope()
 {
 return new Envelope(
 subject: 'Hello Email',
 );
 }
 
 
 
 
 
 
 public function content()
 {
 return new Content(
 view: 'hello',
 );
 }
 
 
 
 
 
 
 public function attachments()
 {
 return [];
 }
 }
 
 | 
建立視圖
新增 resources/views/hello.blade.php 檔。
| 12
 3
 
 | <div>Hello, World!
 </div>
 
 | 
寄送郵件
修改 routes/api.php 檔,新增一個測試路由。
| 12
 3
 
 | Route::get('/', function () {Mail::to('[email protected]')->send(new \App\Mail\HelloEmail());
 });
 
 | 
使用 curl 指令呼叫測試路由,將 HelloEmail 郵件寄送出去。
| 1
 | curl --request GET --url http://127.0.0.1:8000/api
 | 
參考資料