How to send mail using SwiftMailer in php

Swiftmailer library is used for sending mail it’s much similar as PHPMailer. We are going to create SMTP user to send mail here are the steps.

  • Create SMTP user.
  • Install library using composer.
  • Create File for sending mail.

Install using Composer. You can get it from GitHub

composer require swiftmailer/swiftmailer

When installation completed, create new file for sending mail and include autoload.php file.

Create sendmail.php file

<?php
require_once './vendor/autoload.php';
$transport = (new Swift_SmtpTransport(SMTP_SERVER, SMTP_Port))
  ->setUsername(SMTP_Username)
  ->setPassword(SMTP_Password)
;

// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);

// Create a message
$message = (new Swift_Message($subject='Wonderful Subject'))
  ->setFrom([SMTP_Username => $from_mail='John Due'])
  ->setTo($email)
  ->setBody('<h1>This is HTML body text</h1>' ,"text/html");
  
 
// Send the message
$result = $mailer->send($message);

if ($result) {
    echo "Message has been successfully sent!";
}
  • $transport = (new Swift_SmtpTransport(SMTP_SERVER, SMTP_Port))
    ->setUsername(SMTP_Username)

    ->setPassword(SMTP_Password);
  • Swift_SmtpTransport is one type of transport method. Other Transport method like Swift_SendmailTransport, Swift_LoadBalancedTransport and Swift_FailoverTransport.
  • Swift_SmtpTransport is supports Authentications and Encryption. SMTP_SERVER you can ask for your hosting provider.

SwiftMailer send bulk mail.

If you want to send multiple mail by single file run. who are not aware of each others.

// Send the message
$to = ['receiver1@example.com', 'receiver2@example.com' => 'John Deo'];

foreach ($to as $address => $name)
{
  if (is_int($address)) {
    $message->setTo($name);
  } else {
    $message->setTo([$address => $name]);
  }

   $mailer->send($message, $failedRecipients);
}

Conclusion.

We have use Swiftmailer library for sending mail to users. mostly use in registrations, forgot pass, OTP based authentications. So, it useful when you are develop mail sending functionality.

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply