如何通过 Swiftmailer 发送电子邮件

How can I send an email via Swiftmailer

我尝试通过 Symfony Swiftmailer 发送电子邮件:

<?php

namespace App\Service;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class MailGenerator extends AbstractController
{
    public function __construct(\Swift_Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    public function sendMail()
    {
        $message = (new \Swift_Message('Hello Email'))
            ->setFrom('mail@mypage.com')
            ->setTo('mail@mypage.com')
            ->setBody(
                $this->renderView(
                    'mail/mail.html.twig',
                    ['name' => 'test']
                )
            );

        $this->mailer->send($message);

        return $this->render('mail/mail.html.twig');
    }
}

但是我没有收到任何邮件。我错过了什么?

在控制台中测试电子邮件发送:

php bin/console swiftmailer:email:send --to=mail@mypage.com --from=mail@mypage.com --subject=test --body=test

输出结果是什么?

我使用此 Mailer Class 服务发送电子邮件(使用 Google 帐户) 您可以编辑以下配置文件以使用您自己的 smtp 配置

config/services.yaml

parameters:
    mailer:
        smtp_host: 'smtp.gmail.com'
        smtp_port: 587
        smtp_cert: 'tls'
        smtp_username: 'myaccount@gmail.com'
        smtp_password: 'mypassword'

services
    mybase.mailer.services:
        class: App\Services\Mailer
        arguments: ['%mailer%']
        public: true

src/Services/Mailer.php

<?php

/**
 * Service that can be used to send email using basic swift mailer transport
 */

namespace App\Services;

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class Mailer
{
    /**
    * @var array $emailConfig
    */
    private $emailConfig;

    /**
     * Mailer constructor
     * 
     * @param ParameterBagInterface $params
     */
    public function __construct(ParameterBagInterface $params)
    {
        $this->emailConfig = $params->get('mailer');
    }

    public function sendMail(array $mailInfo, string $html, array $files = [])
    {
        $emailConfig = $this->emailConfig;

        $smtpHost   = $emailConfig['smtp_host'];
        $smtpPort   = $emailConfig['smtp_port'];
        $smtpCert   = $emailConfig['smtp_cert'];
        $smtpUsername   = $emailConfig['smtp_username'];
        $smtpPassword   = $emailConfig['smtp_password'];

        $transport = (new \Swift_SmtpTransport($smtpHost, $smtpPort, $smtpCert))
            ->setUsername($smtpUsername)
            ->setPassword($smtpPassword)
        ;

        $swiftMailer = new \Swift_Mailer($transport);

        $message = (new \Swift_Message($mailInfo['title']))
            ->setFrom([$smtpUsername => $mailInfo['senderName']])
            ->setTo($mailInfo['sendTo'])
            ->setBody($html, 'text/html');

        foreach ($files as $file) {
            $message->attach(\Swift_Attachment::fromPath($file));
        }

        $swiftMailer->send($message);
    }
}
  • 使用示例

在另一个服务中

<?php

namespace App\Services;

use App\Services\Mailer;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyOtherService
{
    /**
     * @var \Mailer $mailer;
     */
    private $mailer;

    /**
     * @var \Twig\Environment $templating;
     */
    private $templating;

    /**
     * @var ContainerInterface $container;
     */
    private $container;

    public function __construct(Mailer $mailer, \Twig\Environment $templating, ContainerInterface $container)
    {
        $this->mailer       = $mailer;
        $this->templating   = $templating;
        $this->container    = $container;
    }

    public function methodName()
    {
        // Logic ....

        $params = [
            "sendTo"    => 'myclient@email.com',
            "title"     => "This is my awesome title",
            "senderName"=> 'My company name',
        ];

        $html = $this->templating->render("path/to-my-email/email-template.html.twig", [
            'some_variable' => 'SOME VARIABLES',
        ]);

        $this->mailer->sendMail($params, $html);
    }
}

或来自控制器

public function sendClientEmail(Request $request, Mailer $mailer): Response
    {
        // My code logics

        $params = [
            "sendTo"    => 'myclient@email.com',
            "title"     => "This is my awesome title",
            "senderName"=> 'My company name',
        ];

        $html = $this->render("path/to-my-email/email-template.html.twig", [
            'some_variable' => 'SOME VARIABLES',
        ])->getContent();

        $mailer->sendMail($params, $html);

        // Rest of my code logics
    }