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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (2)

Collapse
 
aniruddhaadak profile image
ANIRUDDHA ADAK

wow amazing .

Collapse
 
skipperhoa profile image
Hòa Nguyễn Coder

Thanks bro

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay