Check mail is sent successfully or not on Laravel 5 - laravel

I have a function that can send mail on Laravel5 using this
/**
* Send Mail from Parts Specification Form
*/
public function sendMail(Request $request) {
$data = $request->all();
$messageBody = $this->getMessageBody($data);
Mail::raw($messageBody, function ($message) {
$message->from('yourEmail#domain.com', 'Learning Laravel');
$message->to('goper.zosa#gmail.com');
$message->subject('Learning Laravel test email');
});
return redirect()->back();
}
/**
* Return message body from Parts Specification Form
* #param object $data
* #return string
*/
private function getMessageBody($data) {
$messageBody = 'dummy dummy dummy dummy';
}
and is sent successfully. But how to check if it was sent or not? Like
if (Mail::sent == 'error') {
echo 'Mail not sent';
} else {
echo 'Mail sent successfully.';
}
I'm just guessing that code.

I'm not entirely sure this would work but you can give it a shot
/**
* Send Mail from Parts Specification Form
*/
public function sendMail(Request $request) {
$data = $request->all();
$messageBody = $this->getMessageBody($data);
Mail::raw($messageBody, function ($message) {
$message->from('yourEmail#domain.com', 'Learning Laravel');
$message->to('goper.zosa#gmail.com');
$message->subject('Learning Laravel test email');
});
// check for failures
if (Mail::failures()) {
// return response showing failed emails
}
// otherwise everything is okay ...
return redirect()->back();
}

Hope this helps
The Mail::failures() will return an array of failed emails.
Mail::send(...)
if( count(Mail::failures()) > 0 ) {
echo "There was one or more failures. They were: <br />";
foreach(Mail::failures() as $email_address) {
echo " - $email_address <br />";
}
} else {
echo "No errors, all sent successfully!";
}
source : http://laravel.io/forum/08-08-2014-how-to-know-if-e-mail-was-sent

For Laravel 9.11.0
Mail::failures() // is deprecated in laravel 9.11.0
To check if your email was sent successfully one could wrap mail send in a try catch block:
try {
Mail::to($userEmail)->send($welcomeMailable);
} catch (Exception $e) {
//Email sent failed.
}
or since Mail::to($email)->send($mailable) on success returns an instance of : SentMessage one could check:
$welcomeEmailSent = Mail::to($userEmail)->send($welcomeMailable);
if ($welcomeEmailSent instanceof \Illuminate\Mail\SentMessage) {
//email sent success
} else {
//email sent failed
}

You may additionally can make use "Swift_TransportException" to identify any errors.
try{
//code to send the mail
}catch(\Swift_TransportException $transportExp){
//$transportExp->getMessage();
}

You can use the Mail::failures() function for that.
It will have a collection of failed mails if it exists so you can use the code below to check for it.
public function sendMail(Request $request) {
$data = $request->all();
$messageBody = $this->getMessageBody($data);
Mail::raw($messageBody, function ($message) use ($messageBody) {
$message->from('yourEmail#domain.com', 'Learning Laravel');
$message->to('goper.zosa#gmail.com');
$message->subject($messageBody);
});
// check for failed ones
if (Mail::failures()) {
// return failed mails
return new Error(Mail::failures());
}
// else do redirect back to normal
return redirect()->back();
}

Related

Laravel Controller Request Verify

Can someone help me verify a request via controller? I don't know how to do this.
public function verify(Request $request){
$key = clean($request->purchasecode);
$response = \Core\Http::url("https://cdn.gempixel.com/validator/";)
->with('X-Authorization', 'TOKEN '.md5(url()))
->body(['url' => url(), 'key' => $key])
->post()
->getBody();
if(!$response || empty($response) || $response == "Failed"){
return back()->with("danger", "This purchase code is not valid. It is either for another item or has been disabled.");
}elseif($response == "TooMany"){
return back()->with("danger", "This purchase code is already used on another domain. If you need to reset it, please us your purchase code and domain to reset it.");
}elseif($response == "Wrong.Item"){
return back()->with("danger", "This purchase code is for another item. Please use a Premium URL Shortener extended license purchase code.");
}elseif($response == "Wrong.License"){
return back()->with("danger", "This purchase code is for a standard license. Please use a Premium URL Shortener extended license purchase code.");
} else {
$setting = DB::settings()->where('config', 'purchasecode')->first();
$setting->var = $key;
$setting->save();
$this->seelfdb($response);
}
}
/**
* Seelfdb:code
*
* #author GemPixel <https://gempixel.com>
* #version 6.0
* #return void
*/
private function seelfdb($r){
$q = str_replace("_PRE_", DBprefix, $r);
$qs = explode("|", $q);
foreach ($qs as $query) {
if(!DB::raw_execute($query)){
return Gem::trigger(500, 'Task failed.');
}
}
return back()->with('success', base64_decode('RXh0ZW5kZWQgdmVyc2lvbiBoYXMgYmVlbiBzdWNjZXNzZnVsbHkgdW5sb2NrZWQuIFlvdSBtYXkgbm93IHVzZSBwYXltZW50IG1vZHVsZXMgYW5kIHN1YnNjcmlwdGlvbnMu'));
}
}
It's a laravel based website. I need to enable payment methods, the only method to do this is by verifying the purchase code. You can see the validator URL in the code. But I want to Bypass or something like this to verify any purchase code to trigger
$setting = DB::settings()->where('config', 'purchasecode')->first();
$setting->var = $key;
$setting->save();
$this->seelfdb($response);
And then I couldn't understand what is this code
private function seelfdb($r){
$q = str_replace("_PRE_", DBprefix, $r);
$qs = explode("|", $q);
foreach ($qs as $query) {
if(!DB::raw_execute($query)){
return Gem::trigger(500, 'Task failed.');
}
}
return back()->with('success', base64_decode('RXh0ZW5kZWQgdmVyc2lvbiBoYXMgYmVlbiBzdWNjZXNzZnVsbHkgdW5sb2NrZWQuIFlvdSBtYXkgbm93IHVzZSBwYXltZW50IG1vZHVsZXMgYW5kIHN1YnNjcmlwdGlvbnMu'));
}

Laravel cannot create cookie from other function

I have this function
function setAuth(){
if(Cookie::has('accesstoken')){
$value = Cookie::get('accesstoken');
echo 'tokense';
return $value;
}
else{
echo 'no token';
$client= new Client();
$response= $client->post('getToken'
]);
$res= json_decode($response->getBody()->getContents()) ;
Cookie::queue(Cookie::make('accesstoken',$res->access_token,10));
return $res->access_token;
}
}
If I call this function like http://localhost:8000/setAuth, this can create cookie.
But in Other function I want to use it like this
function order(Request $request)
{
$client= new Client();
//if get cookie
$token= $this->setAuth();
}
calling order function can't create cookie, Where am I missing.
Queued cookies don't get sent by Laravel until you return a response of some kind.
function order(Request $request)
{
$client= new Client();
//if get cookie
$token= $this->setAuth();
// here we go!
return 'ok';
}

Make an Ajax request in Symfony2

My problem is that the method doesn't return a true result.
I want to test if the email of input exists in my entity or not.
Here is the controller:
public function verificationAction(Request $request)
{
if ($this->container->get('request')->isXmlHttpRequest()) {
$email=$request->request->get('email');
$em=$this->getDoctrine()->getEntityManager();
$resp= $em->getRepository("CMSiteBundle:Prospect")->findBy(array('email'=>$email));
$response =new Response(json_encode($resp));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
You could try an old-trick. Since in Symfony Controller Actions, You must return a Response why not fake a DEAD RESPONSE like so:
<?php
class ABCController {
public function verificationAction(Request $request) {
if ($this->container->get('request')->isXmlHttpRequest()) {
$email = $request->request->get('email');
$em = $this->getDoctrine()->getEntityManager();
$resp = $em->getRepository("CMSiteBundle:Prospect")
->findBy(array('email' => $email));
//$response = new Response(json_encode($resp));
//$response->headers->set('Content-Type', 'application/json');
// THE TRICK IS THAT DIE RUNS FIRST
// THUS SENDS YOUR RESPONSE YOU THEREBY
// STOPPING THE RETURN FROM FIRING... ;-)
return die(json_encode($resp));
}
}
}
Perhaps this very Old Trick still works for you... ;-)

API REST don't work routes

I'm using codeigniter, for make an api rest, with the library that provide the oficial web site.
The problem is: the file routes.php doesn't redirect well. When i put localhost/API/1 into my browser apear the 404 error.
Here my controller "Apicontroller":
public function __construct() { //constructor //no tocar
parent::__construct();
$this -> load -> model("Modelocontrolador");
}
public function index_get() { //get all the info
$datos_devueltos = $this->Modelocontrolador->getPrueba(NULL, "Usuarios");
if(!is_null($datos_devueltos)){
$this->response(array("response" => $datos_devueltos), 200);
}else{
$this->response(array("response" => "No date"), 200);
}
}
public function find_get($id){ //select where
$datos_devueltos = $this->Modelocontrolador->getPrueba($id, "Usuarios");
if($id != NULL){
if(!is_null($datos_devueltos)){
$this->response(array("response" => $datos_devueltos), 200);
}else{
$this->response(array("response" => "No date"), 200);
}
}else{
$this->response(array("response" => "No dates for search"), 200);
}
}
public function index_post() { //insert in la table
if(! $this -> post("dato")){
$this->response(array("response" => "No enought info"), 200);
}else{
$datoID = $this -> Modelocontrolador -> save($this -> post("dato"),"UsuariosJJ");
if(!is_null($datoID)){
$this->response(array("response" => $datoID), 200);
}else{
$this->response(array("response" => "No found it"), 200);
}
}
}
public function index_put($id) { //"update"
if(! $this -> post("dato") || ! $id){
$this->response(array("response" => "No ha mandado informacion correcta para el update"), 200);
}else{
$datoID = $this -> Modelocontrolador -> update("Uid",$id,$this -> post("dato"),"UsuariosJJ");
if(!is_null($datoID)){
$this->response(array("response" => "Dato actualizado"), 200);
}else{
$this->response(array("response" => "Error modify"), 200);
}
}
}
public function index_delete($id) {
if(! $id){
$this->response(array("response" => "Not enought info"), 200);
}else{
$delete = $this-> Modelocontrolador -> delete("Uid",$id,"UsuariosJJ");
}
if(!is_null($delete)){
$this->response(array("response" => "Date delete"), 200);
}else{
$this->response(array("response" => "Error delete"), 200);
}
}}
And my routes file:
$route['default_controller'] = 'Apicontroller';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
/*sub-rutas*/
/*---------*/
$route["Apicontroller"]["get"] = "Apicontroller/index"; //basico
$route["Apicontroller/(:num)"]["get"] = "Apicontroller/find"; //select
$route["Apicontroller"]["post"] = "Apicontroller/index"; //insert
$route["Apicontroller/(:num)"]["put"] = "Apicontroller/index/$1"; //update
$route["Apicontroller/(:num)"]["delete"] = "Apicontroller/index/$1"; //delete
If the browser request literally uses /API then routing needs to 'see' exactly that. Also, the route rules must be explicit with the method to be called. (Hopefully the code shown reflects the mapping you had in mind.)
/*sub-rutas*/
/*---------*/
$route["API"]["get"] = "Apicontroller/index_get"; //basico
$route["API/(:num)"]["get"] = "Apicontroller/find_get/$1"; //select
$route["API"]["post"] = "Apicontroller/index_post"; //insert
$route["API/(:num)"]["put"] = "Apicontroller/index_put/$1"; //update
$route["API/(:num)"]["delete"] = "Apicontroller/index_delete/$1"; //delete
Using the above routes I created some test code. Here are those files.
The much simplified Apicontroller.
class Apicontroller extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index_get()
{
echo "API index";
}
public function find_get($id)
{ //select where
echo "API find_get $id";
}
public function index_post()
{
echo 'API index_post';
}
public function index_put($id)
{ //"update"
echo "API put $id";
}
}
I don't believe that because your Apicontroller is extending a different Class the results would change. That may be a drastic assumption.
In order to test POST calls I used these two files.
First a Testpost.php controller
class Testpost extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('form');
}
public function index()
{
$this->load->view("test");
}
}
The very simple view (test.php) loaded by the above.
<?php
echo form_open("API");
echo form_submit('mysubmit', 'Submit Post!');
echo form_close();
Directing the browser to localhost/testpost shows a page with a single submit button. Pressing the button results in a screen with the text "API index_post".
Sending the browser to localhost/API/3 produces a screen with the text "API find_get 3".
localhost/API produces "API index".
Now the interesting thing (not related to your problem, but interesting).
Given the default
$route['default_controller'] = 'Apicontroller';
and the route
$route["API"]["get"] = "Apicontroller/index_get";
I expected that directing the browser to the home page localhost would produce "API index". But it doesn't. It results in a 404. Due to that behavior it might be wise to be more explicit with default_controller
$route['default_controller'] = 'Apicontroller/index_get';
Or add an index() function to Apicontroller that calls $this->index_get().
I did not test PUT or DELETE as my server isn't setup to handle them. But as GET and POST seem to function, in a righteous world, they will work.
seems like you are using PHil's REST_Controller library with CI 2.x, correct ?
If so, I would recommend you to use what I like to call an "index gateway" because you can't do per-Method routing with CI2:
class Apicontroller extends REST_Controller
{
function index_gateway_get($id){
$this->get_get($id);
}
function index_gateway_put($id){
$this->put_put($id);
}
// This is not a "gateway" method because POST doesn't require an ID
function index_post(){
$this->post_post();
}
function get_get($id = null){
if(!isset($id)){
// Get all rows
}else{
// Get specific row
}
}
function put_put($id = null){
if(!isset($id)){
// a PUT withtout an ID is a POST
$this->post_post();
}else{
// PUT method
}
}
function post_post(){
// POST method
}
}
The routing to make this work is really easy:
$route["API/(:num)"] = "Apicontroller/index_gateway/$1";
That's all you need. Phil's REST Library will redirect to the correct index_gateway_HTTPMETHOD depending on which method is used.
Each index_gateway_HTTPMETHOD will then redirect to the correct method.
As far as I know, this trick is the only way to have CI2 use a single /API/ entry point that works for all HTTP Methods.

Laravel 4 mail class, how to know if the email was sent?

I'm using the new mail class in Laravel 4, does anybody know how to check if the email was sent? At least that the mail was successfully handed over to the MTA...
If you do
if ( ! Mail::send(array('text' => 'view'), $data, $callback) )
{
return View::make('errors.sendMail');
}
You will know when it was sent or not, but it could be better, because SwiftMailer knows to wich recipients it failed, but Laravel is not exposing the related parameter to help us get that information:
/**
* Send the given Message like it would be sent in a mail client.
*
* All recipients (with the exception of Bcc) will be able to see the other
* recipients this message was sent to.
*
* Recipient/sender data will be retrieved from the Message object.
*
* The return value is the number of recipients who were accepted for
* delivery.
*
* #param Swift_Mime_Message $message
* #param array $failedRecipients An array of failures by-reference
*
* #return integer
*/
public function send(Swift_Mime_Message $message, &$failedRecipients = null)
{
$failedRecipients = (array) $failedRecipients;
if (!$this->_transport->isStarted()) {
$this->_transport->start();
}
$sent = 0;
try {
$sent = $this->_transport->send($message, $failedRecipients);
} catch (Swift_RfcComplianceException $e) {
foreach ($message->getTo() as $address => $name) {
$failedRecipients[] = $address;
}
}
return $sent;
}
But you can extend Laravel's Mailer and add that functionality ($failedRecipients) to the method send of your new class.
EDIT
In 4.1 you can now have access to failed recipients using
Mail::failures();
Antonio has a good point about not knowing which failed.
The real questions is success though. You do not care which failed as much as if ANY failed.
Here is a example for checking if any failed.
$count=0;
$success_count = \Mail::send(array('email.html', 'email.text'), $data, function(\Illuminate\Mail\Message $message) use ($user,&$count)
{
$message->from($user->primary_email, $user->attributes->first.' '.$user->attributes->last );
// send a copy to me
$message->to('me#example.com', 'Example')->subject('Example Email');
$count++
// send a copy to sender
$message->cc($user->primary_email);
$count++
}
if($success_count < $count){
throw new Exception('Failed to send one or more emails.');
}
if(count(Mail::failures()) > 0){
//$errors = 'Failed to send password reset email, please try again.';
$message = "Email not send";
}
return $message;

Resources