Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to send email using REST API build in php?

Tags:

php

slim

I am designing REST API in php. I am using slim framework to design API. I want to send a page to send email. This is my code to send email:

$app->get('/sendemail', function () {



 require_once "Mail.php";
 $from = "Sender <[email protected]>";
 $to = "Recipient <[email protected]>";
 $subject = "Hi!";
 $body = "Hi,\n\nHey Recipient, you done it...";
 $host = "my host";
 $username = "myuserid";
 $password = "password";
 $headers = array ('From' => $from,
   'To' => $to,
   'Subject' => $subject);
 $smtp = Mail::factory('smtp',
   array ('host' => $host,
     'auth' => true,
     'username' => $username,
     'password' => $password));

 $mail = $smtp->send($to, $headers, $body);

 if (PEAR::isError($mail)) {
   echo("<p>" . $mail->getMessage() . "</p>");
  } else {
   echo("<p>Message successfully sent!</p>");
  }
 ?>
});

My code of sending email is working if i check this into my separate file. But this code is not working in API.

This is error which is generating :-

enter image description here

please suggest me what should i do for this?

like image 325
Pushpendra Kuntal Avatar asked Apr 08 '26 09:04

Pushpendra Kuntal


1 Answers

Slim approaches PHP errors in a object-oriented way. It transforms all errors into exceptions using PHP standard class ErrorException.

Errors have error levels, such as E_NOTICE or E_WARNING. Exceptions do not. You either have an exception either you don't.

The version of PEAR mailer you are using is raising a minor deprecation notice. Usually it would be hidden and you wouldn't know about it, but since it is transformed to exception, Slim shows you an error. This is a good thing; your code should not have notices.

To solve this you can try updating your mailer class as to avoid deprecated features or you could temporarily catch errors yourself:

function ignoringHandler($level, $str, $file='', $line='', $context=array())
{
    // Tell PHP that we have "processed" the error
    return true;
}

// Change the handler to ours for notices
$slimHandler = set_error_handler('ignoringHandler', E_NOTICE | E_DEPRECATED);

// Your code accessing older library

restore_error_handler();
like image 54
Denis Avatar answered Apr 09 '26 23:04

Denis