尝试在Symfony2中集成sendgrid库时遇到问题。我们已经在我们的包中复制了库,我们已将其包含在服务中。如果某个操作调用了此服务,则它正在成功运行库。
这是服务:
use Symfony\Component\DependencyInjection\ContainerInterface;
require_once(__DIR__.'/SendgridPhp/sendgrid-php.php');
class MailerService extends \Twig_Extension {
protected $container;
private $mailer;
private $templating;
public function __construct(ContainerInterface $container,$mailer,$templating)
{
$this->container= $container;
$this->mailer = $mailer;
$this->templating=$templating;
}
public function sendEmail($to, $from, $subject, $body, $attachment = null)
{
$sendgrid = new \SendGrid($this->container->getParameter('sendgrid_user'), $this->container->getParameter('sendgrid_password'));
$email = new \SendGrid\Email();
$email->setFrom($from)
->setFromName('Name')
->setSubject($subject)
->addTo($to)
->setHtml($body, 'text/html');
$salida = $sendgrid->send($email );
}
}
当我们从symfony2命令调用此服务时,会出现问题。
$mailerService = $container->get('mailer.service');
$mailerService->sendEmail($user->getEmail(), $container->getParameter("sender_email"), 'Message', $body);
命名空间中的错误是下一个:
PHP Fatal error: Class 'SendGrid\Email' not found in /var/www/SpainStartup/src/SpainStartup/CommunicationBundle/Services/MailerService.php on line 35
我们应该在命令上下文中加载库吗?
提前致谢
答案 0 :(得分:0)
您需要自动加载库。第三方代码的文件通常位于vendor文件夹中。您可以将其添加到require
部分中的composer.json:
{
"require": {
// Other dependencies...
"sendgrid/sendgrid": "2.0.5"
}
}
删除您“复制”的内容。然后在您的composer.json文件所在的位置运行composer update
。
在此之后它应该“正常工作”。
答案 1 :(得分:-1)
我没有使用任何sendgrid的库,而是研究了他们在api网站上提供的php示例。这个独立的PHP代码对我来说完美无缺:
<强> sendmail.php 强>
<?php
function sendgridmail($from, $to, $subject, $message, $headers)
{
print_r('entering the function');
$url = 'https://api.sendgrid.com/';
$user='shinujacob';
$pass='mypassword';
$params = array(
'api_user' => $user,
'api_key' => $pass,
'to' => $to,
'subject' => $subject,
'html' => '',
'text' => $message,
'from' => $from,
);
$request = $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
//print_r('obtaining the response');
// obtain response
$response = curl_exec($session);
print_r('closing curl session');
curl_close($session);
// print everything out
//print_r($response);
}
//only for testing:
/*$to = 'shinujacobrocks@yahoo.com';
$subject = 'Testemail';
$message = 'It works!!';
echo 'To is: ' + $to;
#wp_mail( $to, $subject, $message, array() );
sendgridmail($to, $subject, $message, array());
print_r('Just sent!');*/