首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从symfony发送PHP邮件

从symfony发送PHP邮件
EN

Stack Overflow用户
提问于 2020-06-10 19:03:24
回答 1查看 1.1K关注 0票数 1

我想问一下如何从Symfony框架,组件symfony mailer发送PHP mail()。

代码语言:javascript
复制
"symfony/mailer": "5.0.*",

DSN:

代码语言:javascript
复制
MAILER_DSN=mail://localhost

控制器方法:

代码语言:javascript
复制
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!');
}
EN

回答 1

Stack Overflow用户

发布于 2020-06-11 18:48:23

如果我没有理解您的问题,您希望使用新的symfony mailer组件发送电子邮件

前段时间我用邮件组件写了一个mailService,也许你能从中得到一些启发?

代码语言:javascript
复制
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 )

在文档中,您将了解如何处理一些常见的邮件程序或自己进行配置

祝你好运,并享受实验的乐趣:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62301997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档