Laravel sending email - php

I am trying to send an email from my application that uses the Laravel framework. I have installed Sximo as a theme for working with Laravel and the application is running on Amazon AWS. All seems to be good with the setup as it is working as intended.
I have a API setup on *C:\xampp\htdocs\public\api\savequestionnaire.php * that receives data from a mobile application and saves the data to a MySQL table. This also is working as intended.
The idea is that if the API receives some data, an email is generated to a predefined email address. With that, I have a file for receiving the data, writing it to a database and then generating the email as below.
For the Mail section I am following the example on the Laravel website from HERE
savequestionnaire.php
<?php
$json = file_get_contents('php://input');
$questionnairevalues = json_decode($json, true);
$position = $questionnairevalues['position'];
$question_one = $questionnairevalues['question_one'];
$question_two = $questionnairevalues['question_two'];
$question_three = $questionnairevalues['question_three'];
$question_four = $questionnairevalues['question_four'];
$question_five = $questionnairevalues['question_five'];
$query = "INSERT INTO tb_q (position, question_one, question_two, question_three, question_four, question_five) "
. "VALUES('$position', '$question_one', '$question_two', '$question_three', '$question_four', '$question_five')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if ($result) {
echo 'Success';
// Getting error here
Mail::send('emails.contact.blade', $position, function ($message) {
$message->from('myEmail#test.com', 'Laravel');
$message->to('myOtherEmail#test.com');
});
echo '\r\nMail sent success';
}
else {
echo 'Error';
}
mysqli_close($mysqli);
When I run the above code I get the error: "Success
Fatal error: Class 'Mail' not found in C:\xampp\htdocs\public\api\savequestionnaire.php on line 56"
I have also tried adding
use Mail;
to the top of the file but then I get the error: "Warning: The use statement with non-compound name 'Mail' has no effect in C:\xampp\htdocs\public\api\savequestionnaire.php on line 2"
How do I go about implementing the Mail feature correctly using Laravel?
I have also tried using PHP's built in
mail('myEmail#test.com', 'My Subject', 'My message');
function. This generates no errors - but no emails are sent or received.

add this at top of controller:
use Illuminate\Support\Facades\Mail;
In your case directly use :
\Illuminate\Support\Facades\Mail::send('emails.contact.blade', $position, function ($message) {
instead of Mail::send('emails.contact.blade', $position, function ($message) {

In Your Config / app.php Check whether there is
Illuminate\Mail\MailServiceProvider::class,
under providers. And Check Under Aliases you have
'Mail' => Illuminate\Support\Facades\Mail::class,
Edit :
According to the Error, it is looking the facade inside the questionnaire.php you are now in. So try putting this code inside of a controller.
To create a controller, in the terminal type,
php artisan make:controller controllerName

If this page is standalone, you have to use composer to be able to use Mail:
add
require 'vendor/autoload.php';
at the top of your page (replace the path for matching the location of your vendor/autoload.php file

Related

Send Laravel verification email with a custom template using aws ses

What I am trying to do.
My goal is to send a custom blade template for the built-in Laravel email verification functionality. Right now in my AuthServiceProvider inside the boot function I call VerifyEmail::toMailUsing function and attempt to create an email based on the send_email function I already have. it takes a template name, email and params, finds the blade file, and inserts the params and sends the email with aws ses.
VerifyEmail::toMailUsing(function ($notifiable, $url) {
$params = [
'first_name' => $notifiable->first_name,
'verify_url' => $url
];
$generate_email = new SendEmailController();
$generate_email->send_email('verify', $notifiable->email, $params);
});
The issue:
The email gets sent successfully but throws an error:
I understand it must have to do with the toMailUsing, but just cant point my finger to it.
Expected outcome should be: no error :)

Updating config on runtime for a user

I am using Laravel 5.1
I created a function to get smtp info from db for a user $mail_config=STMPDetails::where('user_id',36)->first() and then I can just call config helper function and pass the array to set config value config($mail_config). and then I call Mail::queue function.
but before it reaches createSmtpDriver#vendor/laravel/framework/src/Illuminate/Mail/TransportManager.php where it reads the configuration again to send the mail, mail config are changed to the one specified in .env file.
Another thing to note is Mail sending function is in a Listener
I am not able to figure out where can I call the function such that configuration changes are retained before mail is sent.
Thanks,
K
This should work:
// Set your new config
Config::set('mail.driver', $driver);
Config::set('mail.from', ['address' => $address, 'name' => $name]);
// Re execute the MailServiceProvider that should use your new config
(new Illuminate\Mail\MailServiceProvider(app()))->register();
Since the default MailServiceProvider is a deferred provider, you should be able to change config details before the service is actually created.
Could you show the contents of $mail_config? I'm guessing that's the problem. It should be something like
config(['mail.port' => 587]);
Update - tested in 5.1 app:
Mail::queue('emails.hello', $data, function ($mail) use ($address) {
$mail->to($address);
});
->> Sent normally to recipient.
config(['mail.driver' => 'log']);
Mail::queue('emails.hello', $data, function ($mail) use ($address) {
$mail->to($address);
});
->> Not sent; message logged.

Undefined index cipher on mail from console in Lumen

I am using Lumen ( Laravel 5.1 underneath).
I have a simple code
.
.
.
$this->info( 'sending email to: '. $user->full_name );
Mail::send( 'reminders.attendance', ['user' => $user, 'thisRelation' => $thisRelation ], function ( $m ) use
($user) {
$m->to( $user->email, $user->full_name)->subject('EduStatus Attendance Reminder');
});
I can confirm that there exists a view file. And the email is being triggered when the I put this code in the routes.php file and hit the url simply.
I am trying to make this an artisan command but when I use the same code in my command file it just says
[ErrorException]
Undefined index: cipher
When I remove the mail line, it works just fine. Whatever I print out to the console works.
Any idea?
This was a silly mistake of my own. Somehow I edited the app.php in config folder, the file did not have value for the cipher key.

Laravel pretend is not showing cc mail address

I had change pretend as true in mail config. please check http://laravel.com/docs/4.2/mail#mail-and-local-development
Now log is showing to address like this.
[2014-11-22 17:12:49] production.INFO: Pretending to mail message to: dinukathilanga#gmail.com, bbelekkaya#gmail.com [] []
But i need debug cc emails also. How can i do it?
This is my code.
Mail::send($view, $data, function($message) use ($to, $cc, $subject)
{
foreach ($to as $toUser) {
$message->to($toUser['email'], $toUser['first_name'] . ' ' . $toUser['last_name']);
}
foreach ($cc as $ccUser) {
$message->cc($ccUser['email'], $ccUser['first_name'] . ' ' . $ccUser['last_name']);
}
$message->subject($subject);
});
Allow me to be frank here. I am new to Laravel, but I will try my best to explain this.
I do know how to debug email platforms though, the easiest process is by doing it through C.
I will try to be succint as possible.
Firstly, try using the laravel-debugbar (the latest version is 4).
This is an application that is capable of filtering the PHP Debug Bar.
By using this application you will be able to attach and edit output functions (here is the link for more information: Debug bar.
If this won't work, try debugging through C.
Fristly, you will compile the C program by inserting the debug option, option -g.
Afterwards, you'll launch the gdb into the platform.
Thirdly, you'll break the point in the C program, specifically, insert the break line_number function.
After that, you'll print the variable values in the gdp debugger.
For instance, you'll type commands such as print j and (gdp) p i (I will post the website where I've got this information from; it will give you a more broader walkthrough).
There are various operation for this process.
I strongly advise you visiting:Debug C program using gdb. Hope this helped.
Create a new class named ExtendedMailer for the sake of this example and save the file somewhere the autoloader is able to find it. Depending on where you put the file, you may need to run composer dump-autoload once you've saved it.
<?php
use Illuminate\Mail\Mailer;
class ExtendedMailer extends Mailer
{
protected function logMessage($message)
{
parent::logMessage($message);
$emails = implode(', ', array_keys((array) $message->getCc()));
$this->logger->info("Pretending to mail message to: {$emails}");
}
}
Create a new service provider, somewhere your application is able to load classes. As above, you may need to run composer dump-autoload
The below code simply extends the original MailServiceProvider but allows us to bind a different class to in the IoC, you'll notice the new ExtendedMailer; the class we created earlier. Obviously if you namespaced the class, reflect that change here.
<?php
use Illuminate\Mail\MailServiceProvider;
class ExtendedMailServiceProvider extends MailServiceProvider
{
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
$me = $this;
$this->app->bindShared('mailer', function($app) use ($me)
{
$me->registerSwiftMailer();
// Once we have create the mailer instance, we will set a container instance
// on the mailer. This allows us to resolve mailer classes via containers
// for maximum testability on said classes instead of passing Closures.
$mailer = new ExtendedMailer(
$app['view'], $app['swift.mailer'], $app['events']
);
$this->setMailerDependencies($mailer, $app);
// If a "from" address is set, we will set it on the mailer so that all mail
// messages sent by the applications will utilize the same "from" address
// on each one, which makes the developer's life a lot more convenient.
$from = $app['config']['mail.from'];
if (is_array($from) && isset($from['address']))
{
$mailer->alwaysFrom($from['address'], $from['name']);
}
// Here we will determine if the mailer should be in "pretend" mode for this
// environment, which will simply write out e-mail to the logs instead of
// sending it over the web, which is useful for local dev environments.
$pretend = $app['config']->get('mail.pretend', false);
$mailer->pretend($pretend);
return $mailer;
});
}
}
In your config/app.php, you'll find a line which looks like
'Illuminate\Mail\MailServiceProvider',
You'll need to comment it out and add a line as below
'ExtendedMailServiceProvider',
What this does is replace the mailer which Laravel knows about with the one you've just created. The one you've just created is the same as the default one as it merely extends it, and adds functionality to the logMessage function.

How to use Models in a Laravel Queue

I'm trying to import a mailing list from CSV to my DATABASE. I have two models in my Laravel which is responsible for doing this: Target and Mailing (one Target has many Mailings)
I'm using Queue system with Beanstalkd. I'm using:
Queue::push('ImportCSV', array(
'file' => $file->getClientOriginalName(),
'target' => $name
));
To push my jobs and then I have the ImportCSV job class:
class ImportCSV
{
public function fire($job, $data)
{
Log::info("Starting to add {$data['target']} to database");
$target = new Target();
$target->name = $data['target'];
$target->save();
$reader = new \EasyCSV\Reader($data['file']);
// There must be a Email field in CSV file
/*if(!in_array('Email', $reader->getHeaders() ))
throw new Exception("Email field not found", 1);*/
while ($row = $reader->getRow())
{
$mailing = new Mailing();
$mailing->target()->associate($target);
$mailing->email = $row['Email'];
$mailing->save();
}
Log::info("Mailing list {$target->name} added to database");
$job->delete();
}
}
All the code seems to be working since I get these messages in my Log file
[2013-09-10 21:03:25] log.INFO: Starting to add TEst to database [] []
[2013-09-10 21:03:25] log.INFO: Mailing list TEst added to database [] []
But no records are added to my database. How should I use models inside a job? I already tested it in a Controller for example and everything works fine
Since you don't see other errors, I'm thinking this is an environment issue.
First - environments
Make sure your call to php artisan queue:listen (or queue:work, if applicable) is using the correct environment so the correct database is getting used:
$ php artisan queue:listen --env=YOUR_ENV
Here's a post on setting up queues in Laravel 4 which might be helpful for more information.
Second - namespaces
As you (apparently?) aren't seeing any PHP errors, this is less likely, but another idea:
If your class is namespaced, you may need to use the \ character to get your models, which are in the global namespace.
// From:
$mailing = new Mailing();
// To:
$mailing = new \Mailing();

Categories