Swift_Message::newInstance() not found

This code works when I send email. But when I use Controller class to create route it failed.

$app->get(’/test-email’, function(){

    $message = Swift_Message::newInstance('email api')
                    ->setFrom(array('email@email.com' => 'me'))
                    ->setTo(array('email@email.com' => 'me'))
                    ->setBody('email test')
                    ->setContentType("text/html");
                    if($this->swift_mailer->send($message) == 1){
                      return json_encode(array('error' => false, 'message' => 'message sent'));
                    }
    // Send the message
         return json_encode(array('error' => true, 'message' => 'unable to send message.')); ; 
});

How can I make Swift_Message::newInstance() visible in Controller?

// $app->post(’/test-email’, ‘MailController:postTestMail’);

public function postTestMail($request, $response) {
$message = Swift_Message::newInstance(‘email api’)
->setFrom(array( $request->getParam(‘fromemail’) => ‘joseph’))
->setTo(array( $request->getParam(‘toemail’) => ‘joseph’))
->setBody(‘email api content’)
->setContentType(“text/html”);
if($this->mailer->send($message) == 1){
return json_encode(array(‘error’ => false, ‘message’ => ‘message sent’));
}
// Send the message
return json_encode(array(‘error’ => true, ‘message’ => ‘unable to send message.’));
}

I don’t know if there’s other workaround or good approach for this, I tried to add Swift_Message to container and access it via controller i.e. $this->swift_message to solve this case.

$container[‘swift_message’] = function(){
return Swift_Message::newInstance();
};

problem solved!

What error did you get?

At a guess, your controller is in a namespace, so you need use Swift_Message; at the top of the file.