Email sending in Laravel5 - php

I want to send email from my localhost in laravel 5 using driver: smtp and host: smtp.gmail.com
here is my sample code for sending email after successful account open.
public function postRegister(Request $request)
{
$password = PropertyHelper::randomPassword();
$arrUser = [
'_token' => $request->input('_token'),
'name' => $request->input('name'),
'mobile' => $request->input('mobile'),
'email' => $request->input('email'),
'password' => $password,
'password_confirmation' => $password
];
$validator = $this->registrar->validator($arrUser);
if ($validator->fails())
{
$this->throwValidationException(
$request, $validator
);
}
$data = [
'name' => $request->input('name'),
'password' => $password,
'email' => $request->input('email'),
];
$this->auth->login($this->registrar->create($arrUser));
$data = [
'name' => $request->input('name'),
'password' => $password,
];
$emailSend = Mail::send('emails.signup', $data, function($message){
$message->to(Auth::user()->email)
->subject('নতুন একাউন্ট');
});
dd($emailSend); //output 1
if($emailSend)
{
return redirect($this->redirectPath());
}
}
Here is my config/mail.php file
return [
'driver' => 'smtp',
'host' => 'smtp.gmail.com',
'port' => 587,
'from' => ['address' => 'hizbul25#gmail.com', 'name' => 'Admin'],
'encryption' => 'tls',
'username' => 'myEmail#gmail.com',
'password' => 'gmailPassword',
'sendmail' => '/usr/sbin/sendmail -bs',
'pretend' => false,
];
This code did not show any error but not also send email. If i try to print the out of email send it says 1. Any idea please ??

try to change the mail info inside .inv under root folder instead of mail.php as previous versions of laravel

Related

Cannot send e-mail from queue process

I'm using Yii 2 with the yii2-queue package to send a batch of e-mails from a queue process.
class SendEmailReminder extends \yii\base\BaseObject implements \yii\queue\JobInterface
{
public $userId;
public function execute($queue)
{
$user = \app\models\User::find()
->select(['id', 'email', 'username'])
->where('id=:uid AND verified=false')
->params([':uid' => $this->userId])
->asArray()
->one();
if ($user) {
$body = 'test mail';
Yii::$app->mailer->compose()
->setFrom(Yii::$app->params['fromEmail'])
->setTo('myemail#address')
->setSubject('Reminder')
->setTextBody($body)
->send();
}
}
}
In another controller action I have this:
public function actionRemindUsersWithNoValidatedEmail()
{
$users = User::find()
->select(['id'])
->where(['and', 'verified=false', '(NOW() - registered) > INTERVAL \'6 day\''])
->asArray()
->all();
foreach ($users as $user) {
Yii::$app->queue->push(new SendEmailReminder([
'userId' => $user['id']
]));
}
}
My web.php config:
'components' => [
..............
'queue' => [
'class' => \yii\queue\file\Queue::class,
'path' => '#runtime/queues',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'host',
'username' => 'user',
'password' => 'pass',
'port' => '587',
'encryption' => 'tls',
]
],
]
and my console.php config:
'components' => [
'queue' => [
'class' => \yii\queue\file\Queue::class,
'path' => '#runtime/queues',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'host',
'username' => 'user',
'password' => 'pass',
'port' => '587',
'encryption' => 'tls',
]
],
],
I call the action remind-users-with-no-validated-email and I can see #runtime/queues filling up with the queue files. If I execute ./yii queue/run, I can see that the queue is emptied (thus, processed), but unfortunately no e-mail messages get sent. What am I missing here?
Got it. Because I run ./yii queue/run from the command line, it has trouble to find the base url. So I had to insert this code in console.php (inside the component part):
'urlManager' => [
'class' => 'yii\web\UrlManager',
'scriptUrl' => 'http://myurl'
]
I discovered the error after running ./yii queue/run -v with the verbose flag. Thanks everyone!

Mailgun emails not going out

I'm creating a verification email, however the mail isn't going out and I don't receive any errors.
My call to send the email:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
Mail::to($user->email)
->queue(new VerifyEmail($user));
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
here's my email build function:
public function build()
{
return $this->view('emails.account.verify_email')
->with([
'id' => $this->user->id,
'firstname' => $this->user->firstname,
'token' => $this->user->email_verification_token,
]);
}
I installed guzzlehttp/guzzle
and changed my files:
ENV (not sure of the port setting)
MAIL_DRIVER=mailgun
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=587
MAIL_USERNAME=postmaster#sandbox...655.mailgun.org
MAIL_PASSWORD=Default mailgun sandbox Password
MAIL_ENCRYPTION=tls
config/services
'mailgun' => [
'domain' => env('sandbox...655.mailgun.org'),
'secret' => env('key-...'),
],
config/mail
<?php
return [
'driver' => env('MAIL_DRIVER', 'mailgun'),
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello#example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'sendmail' => '/usr/sbin/sendmail -bs',
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];
I don't receive any errors, however there are no outgoing mails when I check the mailgun dashboard
Your services config file is wrong:
'mailgun' => [
'domain' => env('sandbox...655.mailgun.org'),
'secret' => env('key-...'),
],
You're trying to look up the values from the .env file here. Should reference the keys, not the values. For instance:
'mailgun' => [
'domain' => env('MAIL_DOMAIN'),
'secret' => env('MAIL_SECRET'),
],
And then add them to your .env file:
MAIL_DOMAIN=sandbox...655.mailgun.org
MAIL_KEY=key-...
I'm assuming the rest is correct but I don't know for certain. :)

I'm trying to send email through a contact form

Email error
Swift_TransportException in AbstractSmtpTransport.php line 383:
Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required
"
so far this is my mail.php
<?php
return [
'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'from' => [
'address' => 'hello#example.com',
'name' => 'Example',
],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'sendmail' => '/usr/sbin/sendmail -bs',
];
This is my controller
public function contactstore(Request $request)
{
$data = array_map('trim', $request->all());
$rules = [
'email' => 'required | email',
'name' => 'required',
'msg' => 'required | min:8',
];
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput()->with('error', 'Validation Error.');
}
else {
$data = [
'from' => 'quizmumbai#gmail.com',
'name' => $data['name'],
'email' => $data['email'],
'msg' => $data['msg'],
'view_name' => 'pages.email.querymail',
'to' => 'yogesh696ksingh#gmail.com',
'subject' => 'Event Query for TML 2017',
'timestamp' => date('j/M/Y', time()),
];
Mail::send($data['view_name'], $data, function ($message) use ($data) {
$message->from($data['from'], $data['name']);
$message->to($data['to'])->subject($data['subject']);
});
if (count(Mail::failures()) > 0) {
return redirect()->back()->with('error', 'Cannot send mail');
}
else return redirect()->back()->with('success', 'We will get back to you shortly')->with('message','Thanks for');
}
}
is it because i'm trying on local server?
You must restart your web server to pickup new .env values.

Laravel:sending mail from live server

i have all ok..working in the localhost..the mail is sending from localhost...but when i uploaded it in to the server mail is not coming and no exception is thrown too...here is my .env file code
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=mygmail#gmail.com
MAIL_PASSWORD=mypassword
MAIL_ENCRYPTION=tls
and here is my controller code
protected function create(array $data)
{
//dd($data);
$models = new User;
$user=User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
/*'usertype' =>$data['usertype'],*/
'status' => 0,
]);
$use = array('name' => 'Admin');
//$models->emailw = Auth::user()->email;
$message_id = "";
$name = "";
Mail::send('emailMessage', $use, function ($m) use ($message_id,$name){
$message_id = DB::getPdo()->lastInsertId();
$name = DB::table('users')->select('name')->where('id','=', $message_id)->pluck('name');
//$email = DB::table('users')->select('email')->where('id','=', $message_id)->pluck('email');
$subject = "Id = ". $message_id . " name = " .$name[0];
$m->to('mrbbangladesh2017#gmail.com')
->subject($subject);
});
return $user;
}
and here is my mail.php code
<?php
return [
'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => 'smtp.gmail.com',
'port' => 587,
'from' => [
'address' => 'admin#mrbglobalbd.com',
'name' => 'Admin',
],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'sendmail' => '/usr/sbin/sendmail -bs',
];
what i need to change here?
There can be many things which can go wrong in your condition. I try to list all possible options:
Try port 465 instead of 587 as Gmail normally uses that one.
Check if port is blocked on your live server.
Login to your gmail account( mygmail#gmail.com ). Go to https://myaccount.google.com/security , Scroll down till bottom of page. In right you will see: Allow less secure apps, make sure that option is on.
I hope it helps

Email is not sending in cakephp 3.x in localhost

Here I am trying to send the email from localhost.I have configured the smtp server setting in php.ini and sendmail.ini file as well.And my code changes are
app.php
'EmailTransport' => [
'default' => [
'className' => 'Smtp',
// The following keys are used in SMTP transports
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'timeout' => 30,
'username' => '******',
'password' => '********',
// 'client' => null,
// 'tls' => null,
],
],
'Email' => [
'default' => [
'transport' => 'default',
'from' => '**********',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
],
],
Controller code.
$email = new Email('default');
try {
$res = $email->from('*****#**.**')
->to(['*****#**.**' => 'My Website'])
->subject('Tsting')
->send("hiii this is for testing ");
} catch (Exception $e) {
echo 'Exception : ', $e->getMessage(), "\n";
}

Categories