2016-06-14 175 views
0

我使用Slim PHP框架并尝试通过Gmail发送电子邮件。 问题是当我发送电子邮件时,它会导致“Slim Application Error”。使用SwiftMailer通过Gmail发送电子邮件

$mailer->send($message); 

这里是我的功能来发送电子邮件

function send_email($email) 
{ 
    $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587,'tls') 
     ->setUsername('[email protected]') 
     ->setPassword('yourpassword'); 

    $mailer = Swift_Mailer::newInstance($transport); 


    // Create a message 
    $message = Swift_Message::newInstance('Test mail') 
     ->setFrom(array('[email protected]' => 'SENDER')) 
     ->setTo(array('[email protected]')) 
     ->setBody("Hello, test send mail"); 

    // Send the message 
    $mailer->send($message); 

} 
+1

它抛出了什么错误? – geggleto

+0

教程展示如何使用Swiftmailer配置和发送电子邮件。 http://sgeek.org/send-email-attachment-using-swiftmailer-symfony/ –

回答

0

在你使用它,你必须准备好您的Gmail帐户做到这一点:https://support.google.com/accounts/answer/2461835?hl=en 初始化: //创建交通运输。你可以直接在routes.php中使用它(不是很好的做法),在你的config.php文件中是最好的。 $运输= Swift_SmtpTransport ::的newInstance() - > setHost( 'smtp.gmail.com') - > setPort(465) - > setEncryption( 'SSL') - > setUsername('[email protected] ') - > setPassword('passw') ;

 // Create Mailer instance with our Transport. To be ready to call it. 

$mailer = Swift_Mailer::newInstance($transport); 
</code> 
Using: (Where you need to use it. eg: in UserController.php , you can use it. 
<code> 

    $message = Swift_Message::newInstance() 
        ->setSubject('Email from contact form') 
        ->setFrom(array('[email protected]'=> 'Me')) 
        ->setTo(array('[email protected]' => 'You')) 
        ->setBody("I am sending you an email from contact form"); 

$result = $mailer->send($message); 


    // Print the results, 1 = message sent! 
    print($result); 
</code> 
+1

请为此代码添加一些解释? –

相关问题