我想问一下如何从Symfony框架,组件symfony mailer发送PHP mail()。
"symfony/mailer": "5.0.*",
DSN。
MAILER_DSN=mail://localhost
控制器的方法。
public function test(): Response
{
$transport = new EsmtpTransport('localhost');
$mailer = new Mailer($transport);
$username = $this->getUser()->getUsername();
/** @var Users $user */
$user = $this->getDoctrine()->getRepository(Users::class)->findOneBy(['username' => $username]);
if (!$user)
return new Response("User $username not found! Email not tested.");
$to = $user->getEmail();
if ($to) {
$email = new Email();
$email->from('[email protected]');
$email->to($to);
$email->subject('Test mail');
$email->text('This is test mail from ... for user ' . $to);
$mailer->send($email);
return new Response('Mail send!');
}
return new Response('Mail not sent - user email information missing!');
}
如果我对你的问题理解正确的话,你想使用新的symfony mailer组件来发送邮件。
前段时间我用mailer组件写了一个mailService,也许你能从中得到一些启发 ?
namespace App\Service;
use App\Utils\Utils;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
class MailService
{
private $mailer;
/**
* MailService constructor.
*
* @param $mailer
*/
public function __construct(MailerInterface $mailer)
{
$this->mailer = $mailer;
}
/**
* @param string $renderedView
* @param string $adresse
* @param string $subject
*
* @throws TransportExceptionInterface
* here $renderedview is a a twig template i used to generate my email html
*/
public function sendMail(string $renderedView, string $adresse, string $subject, string $env)
{
if ('dev' !== $env) {
$email = (new Email())
->from([email protected])
->to($adresse)
->subject($subject)
->html($renderedView);
$this->mailer->send($email);
}
}
}
你必须根据你的邮箱参数来配置MAILER_DSN。
( https:/symfony.comdoccurrentcomponentsmailer.html。 )
在文档中,你会发现如何处理一些常见的邮件,或者自己进行配置。
祝你好运,并享受实验的乐趣:)