准备:会使用sendcloud发送邮件 https://blog.csdn.net/sinat_37390744/article/details/88738359
1、app\Notifications\NewUserFollowNotification.php中指定通知类型为email
<?php
namespace App\Notifications;
use App\Channels\SendcloudChannel; //引入邮件处理
use App\Mailer\UserMailer;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Auth;
use Naux\Mail\SendCloudTemplate;
class NewUserFollowNotification extends Notification
{
use Queueable;
public function __construct()
{
//
}
//先database执行toDatabase方法;再sendcloud执行toSendcloud方法
public function via($notifiable)
{
return ['database',SendcloudChannel::class];//默认的Mail不支持sendcloud,但可以自定义channel
}
//自定义的方法,在channel中使用
public function toSendcloud($notifiable){
//封装好的发送邮件类
(new UserMailer())->followNotifyEmail($notifiable->email);
}
public function toDatabase($notifiable){
return [
'name' => \Auth::guard('api')->user()->name,
];
}
public function toArray($notifiable)
{
return [
//
];
}
}
2、app\Channels\SendcloudChannel.php中(自定义notifications的channel)
<?php
namespace App\Channels;
use Illuminate\Notifications\Notification;
class SendcloudChannel
{
public function send($notifiable,Notification $notification){
$message = $notification->toSendcloud($notifiable);//Notification自定义的方法
}
}
3、将邮件发送作为基类
app\Mailer\Mailer.php中
namespace App\Mailer;
use Naux\Mail\SendCloudTemplate;
class Mailer
{
public function sendTo($template,$email,array $data){
$content =new SendCloudTemplate($template,$data);
\Mail::raw($content,function ($message) use ($email){
$message->from('mail@itchuan.net','IThchuan');
$message->to($email);
});
}
}
app\Mailer\UserMailer.php继承上面的基类
namespace App\Mailer;
use App\User;
class UserMailer extends Mailer
{
public function followNotifyEmail($email){
$data = [
];
$this->sendTo('follow_user_templete',$email,$data);//使用基类的发送邮件方法
}
public function passwordReset($email,$token){
$data = [
];
$this->sendTo('pwd_reset_template',$email,$data);
}
public function welcome(User $user){
$data = [
];
$this->sendTo('register_templete',$user->email,$data);
}
}
4、当用户关注时候:
$user->notify(new NewUserFollowNotification());