I set up a contact form which sends an email on completion using Laravel notifications, however it doesn't look like anything is being sent.
ROUTES
Route::post('/contact', 'ContactController#store');
CONTROLLER
public function store()
{
request()->validate([
'name' => 'required|max:255',
'email' => 'required|email|unique:contacts|max:255',
'message' => 'required|max:2000',
]);
$contact = Contact::create(
request()->only([
'name',
'email',
'message',
])
);
User::first()->notify(new SendContactNotification($contact));
return back()->with('success', 'Thank you, I will be in touch as soon as I can');
}
NOTIFICATION
protected $contact;
public function __construct($contact)
{
$this->contact = $contact;
}
public function toMail($notifiable)
{
return (new MailMessage)
->line($this->contact->name)
->line($this->contact->email)
->line($this->contact->message);
}
I do get the success message when I run it. However, nothing appears in my Mailtrap. Here's the mail section of the sanitised .env file:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=username
MAIL_PASSWORD=password
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS='admin#test.com'
MAIL_FROM_NAME='admin'
I can't see what I have done wrong. I also tried type hinting the contact in the notification like so:
public function __construct(Contact $contact)
{
$this->contact = $contact;
}
That didn't work unfortunately. I also thought it might be something to do with my computer not being set up to send emails using php, but I was under the impression that the env file would take care of that.
The contacts are being stored in the database ok, but no emails are being sent. Would anyone be able to help?
It was the port in the env file, I changed it to:
MAIL_PORT=465
and it worked!
I knew port 2525 wasn't working because of this answer: https://stackoverflow.com/a/45418259/5497241
Related
I want to send email verification when a user signs up with a new Email Address. So at the Register Controller I added this:
public function register(Request $request)
{
if(Session::has('email')){
return Redirect::back()->withErrors(['msg' => 'Email was already sent to you, please check the spam folder too.']);
}else{
$validatedEmail = $request->validate([
'user_input' => 'required|unique:users,usr_email|regex:/(.+)#(.+)\.(.+)/i|max:125|min:3',
],[
'user_input.required' => 'You must enter this field',
'user_input.unique' => 'This email is already registered',
'user_input.regex' => 'This email is not correct',
'user_input.max' => 'Maximum length must be 125 characters',
'user_input.min' => 'Minimum length must be 3 characters',
]);
$register = new NewRegisterMemberWithEmail();
return $register->register();
}
}
So if the email was valid, it will call a helper class NewRegisterMemberWithEmail which goes like this:
class NewRegisterMemberWithEmail
{
public function register()
{
try{
$details = [
'title' => 'Verify email'
];
Mail::to(request()->all()['user_input'])->send(new AuthMail($details));
Session::put('email',request()->all()['user_input']);
return redirect()->route('login.form');
}catch(\PDOException $e){
dd($e);
}
}
}
So it used to work fine and correctly sends the email for verification, but I don't know why it does not send email nowadays.
In fact I have tested this with different mail service providers and for both Yahoo & Gmail the email did not received somehow!
But for local mail service provider based in my country the email was sent properly!
I don't know really what's going on here because the logic seems to be fine...
So if you know, please let me know... I would really really appreciate any idea or suggestion from you guys.
Also here is my AuthMail Class if you want to take a look at:
class AuthMail extends Mailable
{
use Queueable, SerializesModels;
public $details;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($details)
{
$this->details = $details;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->subject('Sitename')->view('emails.AuthMail');
}
}
Once I was faced same problem when I was used Gmail as smtp.
Reason:
when we used our Gmail password directly in smtp settings then due to some Gmail policies it'll be blocked after sometime (months) and stopped email sending.
Solution:
we need to create an app-password from our Gmail security and use that password in smtp settings. below google article will guide:
How to create app-password on gmail
.env smtp setting for laravel:
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<your-email>
MAIL_PASSWORD=<app-password>
MAIL_ENCRYPTION=tls
I hope that'll help you.
If you use google mail to send email then we have the same problem.
On May 30, 2022 Google stop supporting less secure applications or third party application.
This is I think the reason why your send mail does not work (consider this answer if you use google mail as mail sender)
I was having issues when sending email, especially to gmail accounts. So I have changed my approach and overcome that issue.
Please check my answer below
Laravel Email
Example Mail Class
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Symfony\Component\Mime\Email;
class OrderInfoMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $data;
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$this
->subject('Order Confirmation')
->from('noreply#app.xxx.co.uk', 'XXX Portal')
->view('orders.templates.order-form')
->with([
'name' => $this->data->name,
'sales_representative_name' => $this->data->sales_representative_name,
'sales_representative_phone' => $this->data->sales_representative_phone,
"items" => $this->data->items,
"address" => $this->data->address,
"net" => $this->data->net,
"payment" => $this->data->payment,
"balance" => $this->data->balance,
]);
$this->withSymfonyMessage(function (Email $message) {
$message->getHeaders()->addTextHeader(
'X-Mailer', 'PHP/' . phpversion()
);
});
return $this;
}
}
Usage
$email = 'a#b.com'; // pls change
$name = 'ab';// pls change
$data = new \stdClass();
$data->name = $name;
$data->sales_representative_name = \App\User::find(Auth::user()->id)->name;
$data->sales_representative_phone = \App\User::find(Auth::user()->id)->phones->first()->number;
$data->items = $order_items;
$data->address = $address;
$data->net = $net;
$data->payment = $payment;
$data->balance = $balance;
Mail::to($email)->send(new \App\Mail\OrderInfoMail($data));
I don't think the issue is your code. I think it is related to you sending practices. A solution is to use a service that is designed to send emails like SparkPost (full disclosure I work for SparkPost). There are many others. These services can help you make sure you are following email best practices.
You can make this work without an email service but at the very least you should verify you are following the best practices presented by MAAWG: https://www.m3aawg.org/published-documents
I am developing my first Laravel app and want to avoid accidentally deploying emails from my dev and local environments to real people, other than myself. My goal is to have a list of comma-separated email addresses in my .env file that the Laravel's Mailable checks against when APP_ENV is not "production".
# .env
APP_ENV=local
EMAIL_WHITELIST=test#example.com
I checked the send method in vendor\laravel\framework\src\Illuminate\Mail\Mailable.php and could modify the code there but have an eerie feeling that I am not supposed to touch that file.
# vendor\laravel\framework\src\Illuminate\Mail\Mailable.php
public function send($mailer)
{
$this->withLocale($this->locale, function () use ($mailer) {
Container::getInstance()->call([$this, 'build']);
$mailer = $mailer instanceof MailFactory
? $mailer->mailer($this->mailer)
: $mailer;
return $mailer->send($this->buildView(), $this->buildViewData(), function ($message) {
$this->buildFrom($message)
->buildRecipients($message)
->buildSubject($message)
->runCallbacks($message)
->buildAttachments($message);
});
});
}
Thanks!
One option is to create an Event Listener and register it with Laravel's MessageSending event. This allows you to perform all manner of actions on each outgoing message before it is sent.
App\Providers\EventServiceProvider
protected $listen = [
'Illuminate\Mail\Events\MessageSending' => [
'App\Listeners\PrepareMessageForSending'
],
];
App\Listeners\PrepareMessageForSending
class PrepareMessageForSending
{
public function handle(MessageSending $event)
{
if (env('APP_ENV') !== 'production') {
// for example, you could redirect everything to a mail trap account
$event->message->setTo('mailtrap#example.com');
}
return $event->message;
}
}
I am trying send email verification links to user when they register but I get a message Authentication required and mail isn't sent. I tried using mailtrap for demo and sendgrid which I will be using in production but the message was the same. This is how I a going about it
After running composer require guzzlehttp/guzzle I updated my env file like this
# MAIL_DRIVER=smtp
# MAIL_HOST=smtp.mailtrap.io
# MAIL_PORT=2525
# MAIL_USERNAME=mailtrap_username
# MAIL_PASSWORD=mailtrap_password
# MAIL_ENCRYPTION=tls
MAIL_DRIVER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=sendgrid_username
MAIL_PASSWORD=sendgrid_password
MAIL_ENCRYPTION=tls
In the controller, I want to send the mail after a user is successfully created like this
...
use App\Mail\VerifyEmail;
...
use Illuminate\Support\Facades\Mail;
public function register(Request $request)
{
// create and store new user record
$user = User::create([
'username' => $request->username,
'password' => bcrypt($request->password)
]);
// send user email verification link
Mail::to($user->username)->send(new VerifyEmail());
}
VerifyMail.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class VerifyEmail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$from = 'support#fromus.com';
$name = 'custom name';
$subject = 'Welcome! Confirm Your Email';
return $this->from($from, $name)
->subject($subject)
->view('auth.verify');
}
}
Following the documentation for email verification https://laravel.com/docs/5.8/verification#verification-routing I added the Auth::routes(['verify' => true]) to api.php file like this
<?php
// Register routes for email verification
Auth::routes(['verify' => true]);
Route::prefix('v1')->group(function () {
// protected routes
Route::middleware('auth:api')->group(function () {
Route::get('products', 'ProductController#index'); // get products
});
});
Route::fallback(function () {
return response()->json(['error' => 'Not Found'], 404);
});
Why am I getting the Authentication required error message and how can I fix it?
First i removed Auth::routes(['verify' => true]) from the api.php file and added it in the web.php.
Then I ran php artisan config:cache to cache changes made to the env file. Fixed
I want to send activation email/code to their emails during signup procedure but I am unable to find suitable answer that help me to complete my work.
This is my controller method where i am saving user data into my database using sentinel.
public function postRegister(Request $request)
{
$user = Sentinel::registerAndActivate($request->all());
return redirect('/');
}
Here i want to sent activation email/code to their email when user signup.
Your any help would be highly appreciated!
public function postRegister(Request $request)
{
$user = Sentinel::register($request->all());
$activation = Activation::create($user);
$this->sendEmail($user, $activation->code);
return redirect('/');
}
private function sendEmail($user,$code)
{
Mail::send('emails.activation',[
'user' => $user,
'code' => $code
], function($message) use ($user){
$message->to($user->email);
$message->subject("Hello $user->first_name,
activate your account.");
});
}
Use this code
use MAIL namespace in your controller moreover don't forget to create email.verify blade in your application path resources\views\email and create smtp detail in .env file.
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=username
MAIL_PASSWORD=password
MAIL_FROM_ADDRESS=your_email#address.com
MAIL_FROM_NAME=YOURNAME
MAIL_ENCRYPTION=null
public function postRegister(Request $request)
{
$verification_code = 111111; // create random number & save it to db ;
$user = Sentinel::registerAndActivate($request->all());
return redirect('/');
$subject = "Please verify your email address.";
Mail::send('email.verify', ['name' => $user->name, 'verification_code' => $verification_code],
function ($mail) use ($user, $subject) {
$mail->from(getenv('FROM_EMAIL_ADDRESS'), "YOUR APPLICATION NAME");
$mail->to($user->email, $user->name);
$mail->subject($subject);
});
}
this is your email.verify blade :
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
</head>
<body>
<div>
Hi {{ $name }},
<br>
Thank you for creating an account with us.
<br>
Your verification code : <b>{{$verification_code}}</b>
<br/>
</div>
</body>
</html>
I have a problem where I can't put in the variables into the Mail::send() function in laravel. Please see the following code:
$first_name = $request->input('first_name'),
$email = $request->input('email'),
//Create account
User::create([
'first_name' => $first_name,
'last_name' => $request->input('last_name'),
'email' => $email,
'password' => bcrypt($request->input('password')),
]);
//Send email to user
Mail::send('emails.test', ['fname' => $first_name], function($message)
{
$message->to($email)
->subject('Welcome!');
});
return redirect()
->route('home')
->with('info', 'Your account has been created and an authentication link has been sent to the email address that you provided. Please go to your email inbox and click on the link in order to complete the registration.');
For some reason the code breaks when it gets to the send email because I receive the error and the data is sent to the database. Why is the variable no longer accessible afterwards?
Any help would be greatly appreciated. Thank you
Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.
Source: http://php.net/manual/en/functions.anonymous.php
In other words, $email has to be inherited like this:
Mail::send('emails.test', ['fname' => $first_name], function($message) use ($email)
{
$message->to($email)
->subject('Welcome!');
});
Note: use ($email) in the first line.