Send Email using SMTP

Pre-requisites: Basic Understanding HTML, PHP and OOP.

In this project,

  • Send an email using SMTP.

 

Send Email using SMTP

  

 

Code Explanation of mail.php

  1. use PHPMailerPHPMailerPHPMailer;

      use PHPMailerPHPMailerSMTP;

      use PHPMailerPHPMailerException;

 

  • Import above mentioned PHPMailer classes into the global namespace.
  • These must be at the top of your script, not inside a function.

 

  1. require 'vendor/autoload.php';

 

  • Load Composer's autoloader.
  1. $mail = new PHPMailer(true);

 

  • $mail object is created for the predefined PHPMailer Class.
  • Passing true as an argument will enable the exceptions.
  1. $mail->Host       = 'smtp.example.com';  

      $mail->SMTPAuth   = true;                 

      $mail->Username   = 'user@example.com' 

      $mail->Password   = 'pwd';    

        

  • Set the SMTP server.
  • Enable SMTP authentication.
  • SMTP username and password.
  1. $mail->setFrom('from@example.com''Mailer');

      $mail->addAddress('smith@example.com''Smith');     //Add a recipient

      $mail->addAddress('chris@example.com');               //Name is optional

      $mail->addReplyTo('john@example.com''Message');

      $mail->addCC('cc@example.com');

      $mail->addBCC('bcc@example.com');

 

  • Add the recipient addresses using above mentioned options.
  • We can easily add more than one recipient for our mailer.
  1. $mail->Subject = 'Mail subject';

      $mail->Body    = 'HTML message body';

      $mail->AltBody = 'Message body in plain text';

      $mail->send();

 

  • Mail Subject and Body is defined according the mail requirement using above methods.
  • Send() method is used to send the mailer via SMTP.

 

Summary

 

In this project, we have learned to send an email using SMTP.

Predefined classes are imported and an instance of PHPMailer is created and is used to define the mail parameters and finally then mail is sent using send() method.

Help Us to Improve our content

Let's Talk
Go back to Previous Course

© 2021 Lecturely.com. All rights reserved.

Lecturely.com – Imagined by Paras Jairath, Developed by P3 Multisolutions & Powered by Network Bulls.