Search code examples
phpsymfonyswiftmailerrfc

How can I make my email username comply with RFC 2822 using swiftmailer in Symfony?


I try to setup the email configuartions for swiftmailer in services.yaml

parameters:
    mailer:
        smtp_host: 'abc123.webthing.myhost.de'
        smtp_port: 587
        smtp_cert: 'tls'
        smtp_username: 'ab12345-laura'
        smtp_password: 'secret'

This is the mailer service:

<?php

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

namespace App\Service;

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

I tested the code like this:

  /**
  * @Route("/_mailer", name="mailer", methods={"GET","POST"})
  */

  public function mailer(MailGenerator $mailGenerator, Request $request) {
    $output = $mailGenerator->sendMail();
    return $output;
  }

I get the error message:

Address in mailbox given [ab12345-laura] does not comply with RFC 2822, 3.6.2.


Solution

  • The problem is here:

    setFrom([$smtpUsername => $mailInfo['senderName']])
    

    This expects the email address of the person sending the mail and their display name. You use $smtpUsername as an email address, but ab12345-laura is not an email address.

    You need something like:

    setFrom(["laura@mail.test" => "Laura Something"])
    

    So, your $mailInfo should not only contain a name, but also an email address to use for the sender and then use for example

    setFrom([$mailInfo['senderEMail'] => $mailInfo['senderName']])