gpt4 book ai didi

php - 如何在 Symfony 中使用 swiftmailer 使我的电子邮件用户名符合 RFC 2822?

转载 作者:行者123 更新时间:2023-12-02 04:41:13 31 4
gpt4 key购买 nike

我尝试在 services.yaml 中为 swiftmailer 设置电子邮件配置

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

这是邮件服务:

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

我测试了这样的代码:

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

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

我收到错误信息:

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

最佳答案

问题出在这里:

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

这需要发送邮件的人的电子邮件地址及其显示名称。您使用 $smtpUsername 作为电子邮件地址,但 ab12345-laura 不是电子邮件地址。

你需要这样的东西:

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

因此,您的$mailInfo 不仅应包含姓名,还应包含用于发件人的电子邮件地址,然后用作示例

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

关于php - 如何在 Symfony 中使用 swiftmailer 使我的电子邮件用户名符合 RFC 2822?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61382750/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com