Programming | 198 Views

How to Integrate PHPMailer into Your Website

's Gravatar
Mar 8, 2022
<?php 
require 'includes/PHPMailer.php';
    require 'includes/SMTP.php';
    require 'includes/Exception.php';
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;
    $mail = new PHPMailer();

    // Message Importing from another file **.
    //$message = file_get_contents('simple-mail.php');

    $mail-&gt;isSMTP();
    $mail-&gt;Host = "smtp.gmail.com";
    $mail-&gt;SMTPAuth = true;
    $mail-&gt;SMTPSecure = "tls";
    $mail-&gt;Port = "587";
    $mail-&gt;CharSet = 'utf-8';
    $mail-&gt;Username = "your_gmail_username";
    $mail-&gt;Password = "your_gmail_password";
    $mail-&gt;Subject = "New Mail";
    $mail-&gt;From = 'No-Reply@example.com';
    $mail-&gt;FromName = 'Anantaraj Khanal';
    $mail-&gt;isHTML(true);

    //if you want to attached a message through another file **.
    //$mail-&gt;MsgHTML($message);

    $mail-&gt;Body = 'your_message';
    $mail-&gt;addAddress('sender_mail_address');


    // Sent mail
    $mail-&gt;send();

    // Condition to sent mail
    if ( $mail-&gt;send() ) {
        echo "Email Sent..!";
    }else{
        echo "Message could not be sent. Mailer Error: "{$mail-&gt;ErrorInfo};
    }

    // To close SMTP
    $mail-&gt;smtpClose();
?>

This code uses the PHPMailer library to send an email using SMTP. Here is an overview of what the code does:

  1. The require statements include the necessary PHPMailer files.
  2. The use statements import PHPMailer classes to the current namespace.
  3. A new instance of PHPMailer is created.
  4. The isSMTP() method sets the mailer to use SMTP.
  5. The Host, SMTPAuth, SMTPSecure, Port, CharSet, Username, and Password properties are set to appropriate values for the SMTP server you want to use.
  6. The Subject, From, FromName, and isHTML properties are set.
  7. The email message body is set using either the MsgHTML method or the Body property.
  8. The recipient email address is added using the addAddress method.
  9. The send method is called to send the email.
  10. A conditional statement checks if the email was sent successfully and displays a message accordingly.
  11. The smtpClose method is called to close the SMTP connection.

To use this code, you need to replace the placeholders your_gmail_username, your_gmail_password, No-Reply@example.com, Anantaraj Khanal, your_message, and sender_mail_address with appropriate values for your use case. Additionally, you need to make sure that the necessary PHPMailer files are present in the includes directory.