DEV Community

Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on

3

Sending Emails with Mailer in PHP + Symfony

Today, I'll demonstrate how to send an email using Symfony's Mailer component in PHP.

Step 1: Install the Required Library
First, install the Symfony Mailer library with the following command:

composer require symfony/mailer
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up Email Configuration in PHP
After installing the library, you can configure the email sender and recipient details in your PHP code as shown below:

use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;

$transport = Transport::fromDsn('smtp://localhost');
$mailer = new Mailer($transport);

$email = (new Email())
    ->from('hello@example.com')
    ->to('you@example.com')
    //->cc('cc@example.com')
    //->bcc('bcc@example.com')
    //->replyTo('fabien@example.com')
    //->priority(Email::PRIORITY_HIGH)
    ->subject('Time for Symfony Mailer!')
    ->text('Sending emails is fun again!')
    ->html('<p>See Twig integration for better HTML integration!</p>');

$mailer->send($email);
Enter fullscreen mode Exit fullscreen mode

Optional: Use Gmail SMTP Settings
To use Gmail’s SMTP, modify the $transport configuration as shown below:

$mail_from = "example@example.com"; 
$pass = urlencode("password"); 
$mail_to = "example@example.com";

// Chúng ta có thể thêm mail cc vào một mảng
$mail_cc_array=array(
    "example12@example.com",
    "example23@example.com",
);
$transport = Transport::fromDsn("smtp://{$mail_from}:{$pass}@smtp.gmail.com:587?encryption=tls");
Enter fullscreen mode Exit fullscreen mode

Step 3: Set Up an Email Template with Twig
If you’d like to use an HTML template for your email, install Twig using the following command:

composer require twig/twig
Enter fullscreen mode Exit fullscreen mode

Then, configure Twig to load templates:

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/Views/templates');
$twig = new Environment($loader);
// date email
$templateData = [
    'subject' => 'LẬP TRÌNH WEBSITE | HOANGUYENIT',
    'name' => 'Hoà Nguyễn Coder',
    'message' => 'Chuyên trang chia sẻ các kiến thức liên quan đến. 
    Lập Trình Website và Phát triển Website',
];
// Render data email to template
$htmlContent = $twig->render('email_template.html.twig', $templateData);

Enter fullscreen mode Exit fullscreen mode

Full Example Code
Here’s the complete code to send an email in PHP:

// Install the library with: composer require symfony/mailer
require_once "Config/database.php"; // you change it "vendor/autoload.php" 

use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

// Configure Twig
$loader = new FilesystemLoader(__DIR__ . '/Views/templates');
$twig = new Environment($loader);

// Email data
$templateData = [
    'subject' => 'WEB DEVELOPMENT | HOANGUYENIT',
    'name' => 'Hoà Nguyễn Coder',
    'message' => 'Sharing insights and knowledge about web development and design.',
];

// Render email content
$htmlContent = $twig->render('email_template.html.twig', $templateData);

// Gmail email & password setup
$mail_from = "example@example.com"; 
$pass = urlencode("password"); 
$mail_to = "recipient@example.com";

// CC emails
$mail_cc_array = [
    "example12@example.com",
    "example23@example.com",
];

$transport = Transport::fromDsn("smtp://{$mail_from}:{$pass}@smtp.gmail.com:587?encryption=tls");
$mailer = new Mailer($transport); 
$email = (new Email())
    ->from($mail_from)
    ->to($mail_to)
    //->cc('cc@example.com')
    ->attachFromPath(__DIR__ . "/Note.txt")
    ->priority(Email::PRIORITY_HIGH)
    ->subject($templateData['subject'])
    ->html($htmlContent); 

// Add each CC email
foreach ($mail_cc_array as $ccEmail) {
    $email->addCc($ccEmail);
}

try {
    $mailer->send($email);
    echo "Email sent successfully!";
} catch (\Exception $e) {
    echo "Failed to send email: " . $e->getMessage();
}

Enter fullscreen mode Exit fullscreen mode

You can view the complete code on Github or watch the guide here:
TikTok
Youtube

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (2)

Collapse
 
aniruddhaadak profile image
ANIRUDDHA ADAK

wow amazing .

Collapse
 
skipperhoa profile image
Hòa Nguyễn Coder

Thanks bro

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more