-1

Symfony2 Email

Với một ứng dụng web, gửi một email đến cho khách hàng hay cho người dùng để confirm lại thông tin hay bất kỳ một hoạt động nào liên quan đến hệ thống không phải là một vấn đề hiếm gặp và khó xảy ra. Trái ngược lại là khác, trong một ứng dụng WEB thì việc gửi một email cho người dùng thì gần như hệ thống nào cũng có và trang WEB nào cũng có. Quá trình này có thể đơn giản với một số người lập trình nhưng cũng có thể phức tạp cho những người lập trình khác. Bài viết này sẽ hướng dẫn các bạn có thể gửi email trong Symfony2 bằng cách định nghĩa các chức năng và những templates cần thiết.

Mailer parameters

Trước tiên, chúng ta cần config một số thông tin của email vào file parameters.yml. File config này sẽ cho hệ thống biết SMTP server sẽ xử dụng Swift Mailer nào. Chúng ta nên tạo một tài khoản của một dịch vụ email bất kỳ để tiến hành gửi mail. Các bạn có thể dùng gmail, mailtrap.io, ... Trong ví dụ này, tôi dùng SendGrid.

Config file parameters.yml với nội dung:

mailer_transport: smtp
mailer_host: smtp.sendgrid.net
mailer_user: your_sendgrid_username
mailer_password: 'your_sendgrid_password'
mailer_port: 587

contact_email: contact@yourapp.com
from_email: hello@yourapp.com
from_name: YourApp

Các bạn có thể thấy, chúng ta thêm vào 3 thông tin là contact email, from email, name. Những thông tin này sẽ giúp cho chúng ta dễ dàng hơn trong quá trình gửi email.

Send emails in Symfony2 using a MailManager

Nếu bạn có một MailManager sẽ vô cùng hữu ích cho chính bạn trong quá trình làm việc. Vì các code bạn dùng để gửi mail sẽ chỉ lưu trữ trong các lớp MailManager này. Khi bạn cần tìm kiểm, sửa chữa, hay update code. Bạn sẽ không phải tiêu tốn quá nhiều thời gian và công sức. Đây là cách bạn có thể xây dựng được một lớp MailManager riêng cho mình.

<?php

namespace AppBundle\Lib;

class MailManager
{
    protected $mailer;
    protected $twig;

    public function __construct(\Swift_Mailer $mailer, \Twig_Environment $twig)
    {
        $this->mailer = $mailer;
        $this->twig = $twig;
    }

    /**
     * Send email
     *
     * @param   string   $template      email template
     * @param   mixed    $parameters    custom params for template
     * @param   string   $to            to email address or array of email addresses
     * @param   string   $from          from email address
     * @param   string   $fromName      from name
     *
     * @return  boolean                 send status
     */
    public function sendEmail($template, $parameters, $to, $from, $fromName = null)
    {
        $template = $this->twig->loadTemplate('AppBundle:Mail:' . $template . '.html.twig');

        $subject  = $template->renderBlock('subject', $parameters);
        $bodyHtml = $template->renderBlock('body_html', $parameters);
        $bodyText = $template->renderBlock('body_text', $parameters);

        try {
            $message = \Swift_Message::newInstance()
                ->setSubject($subject)
                ->setFrom($from, $fromName)
                ->setTo($to)
                ->setBody($bodyHtml, 'text/html')
                ->addPart($bodyText, 'text/plain')
            ;
            $response = $this->mailer->send($message);

        } catch (\Exception $ex) {
            return $ex->getMessage();
        }

        return $response;
    }
}

Trong function sendEmail, bạn có thể dễ dàng định nghĩa một biến $template. Trong giao diện này, bạn có thể tùy ý định nghĩa, sửa đổi theo ý muốn của mình. Giao diện này sẽ được dùng làm nội dung của email bạn gửi, nên hãy làm có tâm 1 chút nhé. ^^.

Define a simple template

Hãy thử tạo một template đơn giản với symfony2.

{# src/AppBundle/Mail/template.html.twig #}

{% block subject %}
    default subject
{% endblock %}

{% block body_text %}
    default text
{% endblock %}

{% block body_html %}
    <p>default body</p>
{% endblock %}

Trong giao diện này bạn hãy định nghĩa ba thành phần cơ bản nhất mà một email luôn có. Đó là subject, html và text.

A sample email sending action

Bây giờ trong tay bạn đã có mọi thứ bạn cần để gửi 1 email. Hãy thử với đoạn mã code này nào. Email sẽ được gửi đến mail from mà bạn đã config trong file parameters.yml. Hãy tạo một form với một số trường như: firstName, lastName, ... Dưới đây là code khi submit form. Các bạn tham khảo nhé. 😃

public function contactAction(Request $request)
    {
        $form = $this->createForm(new ContactType());

        $form->handleRequest($request);

        //this is where we define which template to use
        $template = 'contact';

        if($form->isValid()){
            //Get data from the submitted form
            $data = $form->getData();
            $mail_params = array(
                'firstName' => $data["firstName"],
                'lastName'  => $data["lastName"],
                'message'   => $data["message"],
                'phoneNumber' => $data["phoneNumber"],
                'email'     => $data["email"]
            );

            //grab the addresses defined in parameters.yml
            $to = $this->container->getParameter('contact_email');
            $from =  $this->container->getParameter('from_email');
            $fromName = $this->container->getParameter('from_name');

            //use the MailManager service to send emails
            $message = $this->container->get('mail_manager');
            $message->sendEmail($template, $mail_params, $to, $from, $fromName);

            return $this->redirectToRoute('contact');
        }

        return $this->render('AppBundle:StaticPages:contact.html.twig',array(
            'form' => $form->createView()
        ));
    }

Và đừng quên sửa lại nội dung trong template để hiển thị thông tin ra nhé.

{% extends "AppBundle:Mail:template.html.twig" %}

{% block subject %}
    YourApp Contact Message
{% endblock %}

{% block body_text %}
    {% autoescape false %}
        Name: {{ firstName }} {{ lastName }}
        Message: {{ message }}
        Phone Number: {{ phoneNumber }}
        Email address: {{ email }}
    {% endautoescape %}
{% endblock %}

{% block body_html %}
    {% autoescape false %}
        <p>Name: {{ firstName }} {{ lastName }}</p>
        <p>Message: {{ message }}</p>
        <p>Phone Number: {{ phoneNumber }}</p>
        <p>Email address: {{ email }}</p>
    {% endautoescape %}
{% endblock %}

Chúc mọi người thành công.^^


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí