简体   繁体   中英

How can I send an email via Swiftmailer

I try to send an email via 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');
    }
}

But I did not receive any email. What did I miss?

Test an email sending in console:

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

What will be the output?

I use this Mailer Class service to send email (With Google account) You can edit the following config file to use your own smtp config

In 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

In 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);
    }
}
  • Usage examples

Inside an another service

<?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);
    }
}

Or from a controller

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM