使用SwiftMailer通过Gmail发送电子邮件

I'm using Slim PHP framework and trying to send e-mail via Gmail. The problem is when I am sending the e-mail, it will cause "Slim Application Error."

$mailer->send($message);

Here is my function to send the e-mail

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

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


    // Create a message
    $message = Swift_Message::newInstance('Test mail')
        ->setFrom(array('from_email@gmail.com' => 'SENDER'))
        ->setTo(array('To_email@gmail.com'))
        ->setBody("Hello, test send mail");

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

} 
duanqian1888
duanqian1888 教程显示如何使用Swiftmailer配置和发送电子邮件。sgeek.org/send-email-attachment-using-swiftmailer-symfony
3 年多之前 回复
dsf23223
dsf23223 它抛出了什么错误?
4 年多之前 回复

1个回答

Before you use it, you must prepare your gmail account to do it: https://support.google.com/accounts/answer/2461835?hl=en Initializing: // Create Transport. You can use it in directly in routes.php (not good practice), in your config.php file is best. $transport = Swift_SmtpTransport::newInstance() ->setHost('smtp.gmail.com') ->setPort(465) ->setEncryption('ssl') ->setUsername('emailat@gmail.com') ->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@email.com'=> 'Me'))
                    ->setTo(array('youremail@email.com' => 'You'))
                    ->setBody("I am sending you an email from contact form");

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


    // Print the results, 1 = message sent!
    print($result);
</code>
dongshi1869
dongshi1869 请为此代码添加一些解释吗?
大约 4 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐