Я читал документацию о новой функции laravel проверки электронной почты. Где я могу найти шаблон электронной почты, который отправляется пользователю? Здесь не отображается: https://laravel.com/docs/5.7/verification#after-verifying-emails
Расположение шаблона подтверждения электронной почты Laravel
Ответы (6)
На самом деле они не используют никаких лезвий или файлов шаблонов. Они создают уведомления и пишут для этого код в уведомлениях.
Laravel использует этот метод класса уведомлений VerifyEmail для отправки электронной почты:
public function toMail($notifiable)
{
if (static::$toMailCallback) {
return call_user_func(static::$toMailCallback, $notifiable);
}
return (new MailMessage)
->subject(Lang::getFromJson('Verify Email Address'))
->line(Lang::getFromJson('Please click the button below to verify your email address.'))
->action(
Lang::getFromJson('Verify Email Address'),
$this->verificationUrl($notifiable)
)
->line(Lang::getFromJson('If you did not create an account, no further action is required.'));
}
Если вы хотите использовать свой собственный шаблон электронной почты, вы можете расширить базовый класс уведомлений.
1) Создайте в app/Notifications/
файле VerifyEmail.php
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Lang;
use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailBase;
class VerifyEmail extends VerifyEmailBase
{
// use Queueable;
// change as you want
public function toMail($notifiable)
{
if (static::$toMailCallback) {
return call_user_func(static::$toMailCallback, $notifiable);
}
return (new MailMessage)
->subject(Lang::getFromJson('Verify Email Address'))
->line(Lang::getFromJson('Please click the button below to verify your email address.'))
->action(
Lang::getFromJson('Verify Email Address'),
$this->verificationUrl($notifiable)
)
->line(Lang::getFromJson('If you did not create an account, no further action is required.'));
}
}
2) Добавить в модель пользователя:
use App\Notifications\VerifyEmail;
а также
/**
* Send the email verification notification.
*
* @return void
*/
public function sendEmailVerificationNotification()
{
$this->notify(new VerifyEmail); // my notification
}
Также, если вам нужен шаблон лезвия:
laravel сгенерирует все необходимые представления проверки электронной почты при выполнении команды
make:auth
. Этот вид находится вresources/views/auth/verify.blade.php
. Вы можете настроить это представление по своему усмотрению для своего приложения.
vendor\laravel\framework\src\Illuminate\Auth\Notifications\VerifyEmail::toMail()
методом.
- person laze; 24.10.2018
Ответ уже в комментарии. Отправлено методом toMail()
.
vendor\laravel\framework\src\Illuminate\Auth\Notifications\VerifyEmail::toMail();
За структуру и внешний вид шаблона; также взгляните на эти места, и вы также можете опубликовать, чтобы изменить шаблон:
\vendor\laravel\framework\src\Illuminate\Notifications\resources\views\email.blade.php
\vendor\laravel\framework\src\Illuminate\Mail\resources\views\
Чтобы опубликовать эти места:
php artisan vendor:publish --tag=laravel-notifications
php artisan vendor:publish --tag=laravel-mail
После выполнения этой команды шаблоны почтовых уведомлений будут расположены в каталоге resources/views/vendor
.
Цвета и стиль контролируются файлом CSS в resources/views/vendor/mail/html/themes/default.css
email.blade.php
- это компонент, какой шаблон использует этот компонент и как я могу его настроить? Благодарность
- person Zahra19977; 21.04.2021
Кроме того, если вы хотите перевести стандартную почту VerifyEmail (или other, где используется Lang :: fromJson (...)), вам нужно создать новый файл json в resources / lang / и назвать его, например, ru.json. Он может содержать текст (resources / lang / ru.json) ниже и должен быть действительным.
{
"Verify Email Address" : "Подтверждение email адреса"
}
Послушайте, я очень просто делаю следующие шаги:
В файле маршрута
Auth::routes(['verify' => true]);
В файле AppServiceProvider.php
namespace App\Providers;
use App\Mail\EmailVerification;
use Illuminate\Support\ServiceProvider;
use View;
use URL;
use Carbon\Carbon;
use Config;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Notifications\Messages\MailMessage;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Override the email notification for verifying email
VerifyEmail::toMailUsing(function ($notifiable){
$verifyUrl = URL::temporarySignedRoute('verification.verify',
\Illuminate\Support\Carbon::now()->addMinutes(\Illuminate\Support\Facades
\Config::get('auth.verification.expire', 60)),
[
'id' => $notifiable->getKey(),
'hash' => sha1($notifiable->getEmailForVerification()),
]
);
return new EmailVerification($verifyUrl, $notifiable);
});
}
}
Теперь создайте подтверждение по электронной почте с помощью Markdown
php artisan make:mail EmailVerification --markdown=emails.verify-email
Отредактируйте EmailVerrification по своему усмотрению и файл лезвия.
class EmailVerification extends Mailable
{
use Queueable, SerializesModels;
public $verifyUrl;
protected $user;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($url,$user)
{
$this->verifyUrl = $url;
$this->user = $user;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
$address = '[email protected]';
$name = 'Name';
$subject = 'verify Email';
return $this->to($this->user)->subject($subject)->from($address, $name)->
markdown('emails.verify',['url' => $this->verifyUrl,'user' => $this->user]);
}
}
в блейд-файле измените дизайн по своему усмотрению и используйте verifyUrl для отображения ссылки проверки и $ user для отображения информации о пользователе.
спасибо, удачного кодирования :)
Если уведомление поддерживает отправку по электронной почте, вы должны определить метод toMail в классе уведомлений. Этот метод получит объект, подлежащий уведомлению, и должен вернуть экземпляр Illuminate \ Notifications \ Messages \ MailMessage. Почтовые сообщения могут содержать строки текста, а также «призыв к действию».
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$url = url('/invoice/'.$this->invoice->id);
return (new MailMessage)
->greeting('Hello!')
->line('One of your invoices has been paid!')
->action('View Invoice', $url)
->line('Thank you for using our application!');
}
Вы можете использовать конструктор электронной почты laravel, как описано здесь: https://laravel.com/docs/5.8/notifications#mail-notifications. Laravel позаботится о просмотре электронной почты.