[英]Send PHP mail from symfony
我想問一下如何從 Symfony 框架,組件 symfony 郵件發送 PHP mail()。
"symfony/mailer": "5.0.*",
DSN:
MAILER_DSN=mail://localhost
Controller 方法:
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('test@mydomain.com');
$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組件寫了一個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(your@email.com)
->to($adresse)
->subject($subject)
->html($renderedView);
$this->mailer->send($email);
}
}
}
您將必須根據您的郵件程序參數配置 MAILER_DSN
( https://symfony.com/doc/current/components/mailer.html )
在文檔中,您將找到如何處理一些常見的郵件程序或自己進行配置
祝你好運,玩得開心:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.