First Step of Laravel 12 Email Simple But quick - Mail Message
目前日常開發很常會需要用到Email功能,但有時候我們只是要簡簡單單的做通知,沒有要花太多時間在處理Email 內容的畫面
I usually have to make some simple email feature in my work life. However, it would spend more time if I have to make the email content by myself.
After discussing with ChatGpt LOL and check some document from offical Laravel website這時侯Notifications就可以上場啦!
God Bless I could make it simply with notification in Laravel
Laravel內建Notificaition可以用內建的畫面做Email通知,各位刻板苦手!這484聽起來挺快樂XD
There is notification feature in Laravel which is with basic email content, so that you dont have to make it by yourself
首先我們先建立我們要用的通知
First, lets build the notification we need
php artisan make:notification MyTestNotification
這時候你會得到一個mail message
You will have a maill message after the command you use.
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class MyTestNotification extends Notification
{
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('來自 Artisan Command 的通知')
->greeting('哈囉!')
->line('這是從 Laravel Command 發送的通知')
->action('點我看看', url('/'))
->line('感謝您的使用!');
}
}
這時你可以發現你可以透過內建預設的function新增你需要的內容
- subject 標題
- line 文字內容
- action 按鈕
Now you could easily find out that you could assign the subject and content by those function.
那最後我們要怎麼把Email寄出去呢
So how could we send the email out now?
在需要寄出的地方
At the Place We need to send our email
- 當我們Email List不在DB的時候
(case when the email list is not from database)
use Illuminate\Notifications\AnonymousNotifiable;
use App\Notifications\MyTestNotification;
public function handle()
{
$emails = [
'no-user1@example.com',
'no-user2@example.com',
];
foreach ($emails as $email) {
(new AnonymousNotifiable)
->route('mail', $email)
->notify(new MyTestNotification());
$this->info("已寄送通知至 {$email}");
}
}
- 當我們Email List在DB的時候
case when email list is from database
use App\Models\User;
use App\Notifications\MyTestNotification;
public function handle()
{
$emails = [
'user1@example.com',
'user2@example.com',
'user3@example.com',
];
$users = User::whereIn('email', $emails)->get();
foreach ($users as $user) {
$user->notify(new MyTestNotification());
$this->info("通知已發送給 {$user->email}");
}
if ($users->isEmpty()) {
$this->error("沒有找到任何使用者");
}
}