使用 Swiftmailer 通过 Symfony2 命令从本地主机发送邮件

Send mail from localhost via Symfony2 Command using Swiftmailer

命令函数

$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;

当我在命令行中执行命令时,我得到 true 就像邮件已发送一样。

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 中删除了假脱机并添加了端口和加密。

# 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,当然也必须对您的应用进行身份验证。 通过这个 link https://myaccount.google.com/security

有link

app password

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

单击此处后,您需要为您的应用指定自定义名称并生成您将在

中使用的新密码

Parameters.yml >> mailer_password:

将应用程序与 gmail 帐户关联。