Как я могу отправить электронное письмо через Swiftmailer - PullRequest
0 голосов
/ 22 апреля 2020

Я пытаюсь отправить электронное письмо через Symfony Swiftmailer:

<?php

namespace App\Service;
use Swiftmailer\Swiftmailer;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

/**
* Mail Generator
*
*/


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

}

Но я не получил ни одного письма. Что я пропустил?

Ответы [ 2 ]

1 голос
/ 22 апреля 2020

Я использую этот сервис Mailer Class для отправки электронной почты (с учетной записью Google). Вы можете отредактировать следующий файл конфигурации, чтобы использовать собственную конфигурацию smtp

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

В 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
    }
1 голос
/ 22 апреля 2020

Проверка отправки электронной почты в консоли:

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

Каким будет вывод?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...