I am taking over a project and a client wants me to add a mailing feature like a gmail with inbox, sent messages and the user can also reply to emails from outside the system and the people receiving it can also reply. I have basic knowledge on laravel but this is my first time creating a feature like this can anyone give a stepping stone. This project has a VUE.js as a front end and a laravel as an API
Step -1: Create a Mail using,
php artisan make:mail MailName
Check the file MailName.php inside App/Mail/ directory
Step - 2: Create a function to send the email with the requested data.
public function sendMail(Request $request){
$data = [
'value1'=> $request->value1,
'value2'=> $request->value2,
'value3'=> $request->value3
];
//You can add any function like storing the values into db.
if(someconditions){
\Mail::to('emailid#domainname.com')->send(new MailName($data));
return back()->with('success', 'Email has been sent successfully!');
}
else
{
return back()->with('error', 'Something went wrong!');
}
}
Step - 3: Open the App/Mail/MailName.php
<?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;
use Illuminate\Mail\Mailables\Address;
//You can include your model here.
class DeleteResponseMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $data;
public function __construct($data)
{
$this->data = $data;
}
/**
* Get the message envelope.
*
* #return \Illuminate\Mail\Mailables\Envelope
*/
public function envelope()
{
return new Envelope(
from: new Address('fromemail#somedomain.com', 'From Email Name'),
replyTo: [
new Address('admin#yourdomain.com', 'Your email name'),
],
subject: 'Email Subject',
);
}
/**
* Get the message content definition.
*
* #return \Illuminate\Mail\Mailables\Content
*/
public function content()
{
return new Content(
view: 'emails.mail',
);
}
/**
* Get the attachments for the message.
*
* #return array
*/
public function attachments()
{
return [];
}
}
Step - 4: Create mail.blade.php under resources/views/emails
Hi $data['value1'],
We have received your application. Thanks!
Step - 5: Open your .env file and add the email configurations.
MAIL_MAILER=enteryourmailerhere (ex.smtp)
MAIL_HOST=enteryourmailhosthere (ex.smtp.gmail.com)
MAIL_PORT=entertheport (ex. 25)
MAIL_USERNAME=emailid#yourdomain.com
MAIL_PASSWORD=emailpassword
MAIL_ENCRYPTION=""
MAIL_FROM_ADDRESS="fromemail#yourdomain.com"
MAIL_FROM_NAME="${APP_NAME}"
That's all! It should work.
Related
I have an laravel 7 application and use smtp with google services to send my emails.
However some clients receive the emails with attachments, but no body. The content of the email is completely blank. Most mail platforms (hotmail, outlook, gmail, mail on mac) receive the complete email. It's just some mail providers receive the email without a body.
I believe this might have to do with some security measures or not supporting HTML emails.
How can I ensure that also these clients receive my emails?
I use .blade.php files to send my emails.
example of one of my email files:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class CandidateMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($message_details)
{
//
$this->message_details = $message_details;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$email = $this->view('mail/candidate')
->subject($this->message_details['subject'])
->with(['message_details' => $this->message_details]);
if ($this->message_details['attachments']) {
$email->attachFromStorage($this->message_details['attachments']);
}
return $email;
}
}
Fix for outlook (desktop).
replaced my divs with table/tr/td. Now email content is displayed to clients with outlook (desktop).
you had to build your constructor the variable $message_details does not return anything,
public $message_details = "";
Need to declare public property public $message_details here details
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class CandidateMail extends Mailable
{
use Queueable, SerializesModels;
public $message_details;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($message_details)
{
//
$this->message_details = $message_details;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$email = $this->view('mail/candidate')
->subject($this->message_details['subject'])
->with(['message_details' => $this->message_details]);
if ($this->message_details['attachments']) {
$email->attachFromStorage($this->message_details['attachments']);
}
return $email;
}
}
I'm in the process of implementing fortify into my app. I'm really confused about customising the default emails that are produced when you hit the password-reset / verifty-email routes?
I could edit them in vendor but that going to cause me an issue every time I update.
There must be a hook to provide an alternative email template.
Unfortnatly I cant find any documentation that explains how its done.
Do I need to add:
public function sendEmailVerificationNotification()
{
}
To my user model? If so how to I generate the return verificaiton URL as its not being held in the database?
Any help would be great.
Thanks!
Here is the solution in Laravel 8.
1.) Create a Notification by command
php artisan make:notification ResetPasswordNotification
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Lang;
class ResetPasswordNotification extends ResetPassword
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public $token;
public function __construct($token)
{
$this->token = $token;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
if (static::$toMailCallback) {
return call_user_func(static::$toMailCallback, $notifiable, $this->token);
}
$url = url(config('app.url') . route('password.reset', [
'token' => $this->token,
'email' => $notifiable->getEmailForPasswordReset(),
], false));
return (new MailMessage)
->view(
'emails.reset_password', ['name'=>$notifiable->name,'url' => $url]
)
->subject(Lang::get('Reset Password'));
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
2.) In the app/Models/User.php Model. Add below method.
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPasswordNotification($token));
}
3.) Now create an email template in views/emails/reset_password.blade.php
Hi {{ $name }}, Please reset your password here. Click on the below link to reset the password.
RESET
You can customize the password reset email by adding the following in FortifyServiceProvider
ResetPassword::toMailUsing(function($user, string $token) {
return (new MailMessage)
->subject('Reset Password')
->view('emails.password_reset', [
'user' => $user,
'url' => sprintf('%s/users/password_reset/%s', config('app.url'), $token)
]);
});
Create a file named resources/views/emails/password_reset.blade.php, in this file you can use $user and $url
You can enter the directory when you use fortify vendor\laravel\framework\src\Illuminate\ Notifications\resources\views\email.blade.php and overwrite the content and style of the email.
Notifications are by default in the directory vendor\laravel\framework\src\Illuminate\Auth\Notifications\VerifyEmail.php
You can change the email text lines there. Similarly reset password in ResetPassword.php
I have Super-Admin and Admin roles. In Admin view I've added button to request verification email. The problem I'm having is that when Admin clicks the button to receive verification email, the email is from Admin, not Super-Admin.
How to make this to be sent to Admin from Super-Admin, instead of from Admin?
Route:
Route::post('/dashboard/SendEmailVerification', 'AdminDashboardController#SendEmailVerification')->name('dashboard.SendEmailVerification');
In AdminDashboardController:
use App\Notifications\EmailVerification;
use App\User;
.............
public function SendEmailVerification(Request $request){
$user = User::where('email_verification_code', $request->code)
->withoutGlobalScope('active')
->first();
$user->notify(new EmailVerification($user));
return Reply::success('Email sent!');
}
And the notification email:
namespace App\Notifications;
use App\Traits\SmtpSettings;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use App\User;
class EmailVerification extends Notification implements ShouldQueue
{
use Queueable, SmtpSettings;
protected $user;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
$this->setMailConfigs();
}
/**
* Get the notification's delivery channels.
*t('mail::layout')
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
$via = ['mail'];
return $via;
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Confirm your email')
->greeting(__('Hello!'))
->line(__('email.emailVerify.text'))
->action('Confirm', getDomainSpecificUrl(route('front.get-email-verification', $this->user->email_verification_code), $this->user->company));
#->line(__('email.thankyouNote'));
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return $notifiable->toArray();
}
}
You're getting wrong sender address because you never defined who's the sender in your Notification configuration. There are two ways to do this:
First: The first one is a really simple, but non-dynamic solution. In your .env configuration config, add these lines:
MAIL_FROM_NAME="My Name"
MAIL_FROM_ADDRESS=support#example.com
When you configure this, add this in yout config/mail.php configuration:
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'default value if not found in .env'),
'name' => env('MAIL_FROM_NAME', 'default value if not found in .env'),
],
Note: Don't forget to clear your cache, and restart queue when you do this:
Second: This is a more dynamic solution, since you can load the sender email address from your database. In your SendEmailVerification method, you can query up the super-admin user, and pass to the EmailVerification class:
public function SendEmailVerification(Request $request){
$user = User::where('email_verification_code', $request->code)
->withoutGlobalScope('active')
->first();
$superAdminUser = User::where('role', 'super-admin')->first();
$user->notify(new EmailVerification($user, $superAdminUser));
return Reply::success('Email sent!');
}
Then, change your EmailVerification class:
public $user;
public $superUser;
public function __construct(User $user, User $superUser)
{
$this->user = $user;
$this->superUser = $superUser;
$this->setMailConfigs();
}
And in your toMail() method, add another from() method:
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Confirm your email')
->from($superAdminUser->email, $superAdminUser->first_name)
->greeting(__('Hello!'))
->line(__('email.emailVerify.text'))
->action('Confirm', getDomainSpecificUrl(route('front.get-email-verification', $this->user->email_verification_code), $this->user->company));
#->line(__('email.thankyouNote'));
}
Note: Also clear your cache and restart your queue.
Hope that this can resolve your issue. Let me know if you have any problems with these solutions.
You can read more about notifications on official documentation.
I have a receiveEmail boolean field in the User model of a Laravel application. How do I ensure that mail notifications respect this field, and only sends the email to the user if the field is true?
What I want is that this code:
$event = new SomeEvent($somedata);
Auth::user()->notify($event);
where SomeEvent is a class that extends Notification and implements 'mail' on the via() method, only sends an email if the user has allowed emails.
Have any one checked this via() method:
https://laravel.com/docs/6.x/notifications#specifying-delivery-channels
public function via($notifiable)
{
// $notifiable object is User instance for most cases
$wantsEmail = $notifiable->settings['wants_email']; // your own logic
if(!$wantsEmail){
// no email only database log
return ['database'];
}
return ['database', 'mail'];
}
I hope this will work while sending notifications to multiple users too. Thanks
I ended up creating a new Channel that implements the checking. In app/channels, add your channel, something like this:
namespace App\Channels;
use App\User;
use Illuminate\Notifications\Channels\MailChannel;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Arr;
class UserCheckMailChannel extends MailChannel
{
/**
* Send the given notification.
*
* #param mixed $notifiable
* #param \Illuminate\Notifications\Notification $notification
* #return void
*/
public function send($notifiable, Notification $notification)
{
// check if user should receive emails. Do whatever check you need here.
if ($notifiable instanceof User && !$notifiable->receiveEmails) {
return;
}
// yes, convert to mail and send it
$message = $notification->toMail($notifiable);
if (!$message) {
return;
}
parent::send($notifiable, $notification);
}
}
Then bind your class on Providers/AppServiceProvider.php to the old mail class:
/**
* Register any application services.
*
* #return void
*/
public function register()
$this->app->bind(
\Illuminate\Notifications\Channels\MailChannel::class,
UserCheckMailChannel::class
);
}
try to create new method in user model like this..
user model file..
public function scopeNotifyMail() {
if($this->receiveEmail == true) { //if field is enable email other wise not send..
$event = new SomeEvent($somedata);
$this->notify($event);
}
}
and now call like this in controller..
Auth::user()->notifyMail();
or
App\User::find(1)->notifyMail();
or
App\User::where('id',1)->first()->notifyMail();
I have been reading from the documentation about the new feature of laravel the email verification. Where can I locate the email template that is sent to the user? It does not show here: https://laravel.com/docs/5.7/verification#after-verifying-emails
Laravel uses this method of VerifyEmail notification class for send email:
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.'));
}
Method in source code.
If you wanna use your own Email template, you can extend Base Notification Class.
1) Create in app/Notifications/ file 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) Add to User model:
use App\Notifications\VerifyEmail;
and
/**
* Send the email verification notification.
*
* #return void
*/
public function sendEmailVerificationNotification()
{
$this->notify(new VerifyEmail); // my notification
}
Also if you need blade template:
laravel will generate all of the necessary email verification views
when the make:auth command is executed. This view is placed in
resources/views/auth/verify.blade.php. You are free to customize
this view as needed for your application.
Source.
Answer in comment already. Sent by the toMail() method.
vendor\laravel\framework\src\Illuminate\Auth\Notifications\VerifyEmail::toMail();
For template structure and appearance; take a look at this locations also and you can also publish to modify the template:
\vendor\laravel\framework\src\Illuminate\Notifications\resources\views\email.blade.php
\vendor\laravel\framework\src\Illuminate\Mail\resources\views\
To publish those locations:
php artisan vendor:publish --tag=laravel-notifications
php artisan vendor:publish --tag=laravel-mail
After running this command, the mail notification templates will be located in the resources/views/vendor directory.
Colors and style are controlled by the CSS file in resources/views/vendor/mail/html/themes/default.css
Also, if you want to translate standard mail VerifyEmail (or other where use Lang::fromJson(...)), you need create new json file in resources/lang/ and name it ru.json, for example.
It may contain (resources/lang/ru.json) text below and must be valid.
{
"Verify Email Address" : "Подтверждение email адреса"
}
Actually they do not use any blade or template files. They create notifications and write code for it in notifications.
Look I do that very easy
do the following steps :
In Route File
Auth::routes(['verify' => true]);
In AppServiceProvider.php File
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);
});
}
}
Now Create EmailVerification With Markdown
php artisan make:mail EmailVerification --markdown=emails.verify-email
Edit The EmailVerrification as you want and the blade file
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 = 'mymail#gmail.com';
$name = 'Name';
$subject = 'verify Email';
return $this->to($this->user)->subject($subject)->from($address, $name)->
markdown('emails.verify',['url' => $this->verifyUrl,'user' => $this->user]);
}
}
in the blade file change the design as you want and use verifyUrl to display the verification link and $user to display user information
thanks, happy coding :)
vendor\laravel\framework\src\Illuminate\Mail\resources\views\html
You will find the Laravel default email template in this file location.
If a notification supports being sent as an email, you should define a toMail method on the notification class. This method will receive a $notifiable entity and should return a Illuminate\Notifications\Messages\MailMessage instance. Mail messages may contain lines of text as well as a "call to action".
/**
* 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!');
}
You can use the laravel e-mail builder as documented here: https://laravel.com/docs/5.8/notifications#mail-notifications. Laravel will take care of the e-mail view.