编程语言
首页 > 编程语言> > php – 使用Swiftmailer通过Symfony2 Command从localhost发送邮件

php – 使用Swiftmailer通过Symfony2 Command从localhost发送邮件

作者:互联网

命令功能

$message = \Swift_Message::newInstance('test')
            ->setContentType("text/html")
            ->setFrom('x@x.com')
            ->setTo('x@gmail.com');

        $message->setBody('test');

        if ($this->getApplication()->getKernel()->getContainer()->get('mailer')->send($message))
        {
            return true;
        }
        return false;

当我在命令行执行命令时,我发送邮件是真的.

Paramters.yml

mailer_transport: gmail
mailer_host: smtp.gmail.com
mailer_user: x@gmail.com
mailer_password: xxxxxxxxxxxxx

Config.yml

swiftmailer:
    spool:
        type: file
        path: "%kernel.root_dir%/../swiftmailer"
    transport: %mailer_transport%
    host:      %mailer_host%
    username:  %mailer_user%
    password:  %mailer_password%

我曾在某处读过可以使用Symfony Profiler来查看邮件是否已发送但我只是想在测试目的中将邮件物理地发送到我的地址.我只需要知道我做错事的地方.

我必须注意到我在gmail帐户中使用了允许的设备安全工具.

这可能是邮件未发送的原因吗?

解决方法:

是!我找到了解决方案.

我在Config.yml中删除了spool并添加了端口和加密.

# Swiftmailer Configuration
swiftmailer:
    transport: %mailer_transport%
    host:      %mailer_host%
    port:      %mailer_port%
    encryption: %mailer_encryption%
    username:  %mailer_user%
    password:  %mailer_password%

并在Parameters.yml中

mailer_transport: gmail
mailer_host: smtp.gmail.com
mailer_port: 465
mailer_encryption: ssl
mailer_user: yourMail@gmail.com
mailer_password: yourNewGeneratedAppPassword

之后,我可以看到错误使用

 $mailer = $this->getContainer()->get('mailer');

 $logger = new \Swift_Plugins_Loggers_ArrayLogger();
 $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));

然后在发送消息之后我使用了:

 echo $logger->dump();

在终端中打印错误.

以下是整体功能.

public function sendMail($email, $data)
    {
        $mailer = $this->getContainer()->get('mailer');

        $logger = new \Swift_Plugins_Loggers_ArrayLogger();
        $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));

        $message = \Swift_Message::newInstance('test')
            ->setContentType("text/html")
            ->setFrom('x@mdpi.com')
            ->setTo($email);

        $message->setBody($data);

        if ($mailer->send($message))
        {
            echo $logger->dump();
            return true;
        }
        return false;
    }

提示:

此外,如果您使用Gmail,您必须验证您的应用程序.
通过此链接https://myaccount.google.com/security

有链接

app password

这是描述https://support.google.com/accounts/answer/185833?hl=en

点击后,您需要为您的应用程序提供自定义名称,并生成您将使用的新密码

Parameters.yml >> mailer_password:

将应用程序与Gmail帐户连接.

标签:swiftmailer,php,symfony,email,command-line
来源: https://codeday.me/bug/20190824/1703590.html