how to send mail in php using phpmailer?




  • user-image:Vinay Kumar
  • Vinay Kumar      Co-Founder Queryflag.com    Answered

  • When we develop a web application where we often need to develop an email communication system where the service provider can connect with the client or vice versa. This is very helpful when we need to send a large number of emails (bulk email) to our clients. Here sending of email goes through its own web server so Let's send an email in PHP using the PHPmailer library


     

    with the SMTP server of Gmail smtp.gmail.com believe me it is very easy if you follow all these steps

    Step 1. Download the PHP mailer library from GitHub and install it

    Step 2. Write the code for sending the email

    Step 3. Fix errors that occur when we send an email

     

    Before starting these steps we must have to know
     

     A. what is the phpmailer library?

     PHP mailer is open source and the most popular code library which is written in PHP. In this library, a lot of methods define by which we can send emails from PHP. it is very safe and efficient for sending emails easily with a web server its many features like

    • integrate with the SMTP server
    • send an email with multiple To, Cc, Bcc, and reply-to address
    • send an HTML document or add an attachment

     

    B. What are SMTP and Gmail smtp server smtp.gmail.com

    SMTP(simple mail transfer protocol) is a protocol for sending an email across the network(between servers)

    SMTP is a mail server that simply checks authentication and delivers email to the receiver mail server

    finally, we know for sending an email we need an SMTP server. smtp.gmail.com  is an SMTP server that Gmail is used for sending emails. Google allows us to send an email with our own web server like localhost. so here we can use the smtp.gmail.com server that operates over port 587.

    I hope we are familiar with phpmailer library and SMTP. so let's start above three-step

     

    step 1. Download phpmailer library from GitHub and install it

    → Go to Google and write phpmailer the first link is  https://github/PhpMailer/PhpMailer,  click on it now here many versions of the library are available select the 5.2 stable version from the tab select branch master and download its zip file

    When it is downloaded extract it. here we need only three files which are found inside  PhpMailer→PhpMailer 

    1. class.phpmailer.php
    2.  class.smtp.php 
    3. PHPMailerAutoload.php

    Now in our application create a new folder phpmailer and copy all these three files and paste them over it. our step 1 is completed now we follow Step 2.

     step 2. Write the code to send the email

       →Here is the code for sending an email copy it and save in php file with any name like sendphpmail.php 

     #Code Start   

    //import PHPMailerAutoload.php file which is located inside phpmailer folder
     require 'phpmailer/PHPMailerAutoload.php';

    // create object of class PHPMailer
      $mail = new PHPMailer;
     
    // print client server communication output if we don't want to print it we can use 3
      $mail->SMTPDebug = 4;  
     
    // Set mailer to use SMTP
      $mail->isSMTP(); 
      
    // Specify main and backup SMTP servers 
      $mail->Host = 'smtp.gmail.com';
      
    // Enable SMTP authentication
      $mail->SMTPAuth = true;
      
    // SMTP username mainly it is sender gmail replace 'techifind@gmail.com' with your gmail   
      $mail->Username = 'techifind@gmail.com'; 
      
    // SMTP password it is your gmail password
      $mail->Password = 'your_gmail@password';
      
    // Enable TLS encryption, `ssl` also accepted
      $mail->SMTPSecure = 'tls';  

    // TCP port to connect to 
      $mail->Port = 587;
      
    // set from it show in from of your mail 
      $mail->setFrom('techifind@gmail.com', 'vinay kumar');
      
    // Add a recipient it is address where you want to send your email you can add multiple here
      $mail->addAddress('vinaykch123@gmail.com');     
    // $mail->addAddress('ellen@example.com');   // to send multiple email

    // set reply to 
      $mail->addReplyTo('vinaykch123@gmail.com', 'no-reply');
      
    //set cc or bcc it is optional   
    //$mail->addCC('cc@example.com');
    //$mail->addBCC('bcc@example.com');

    // Add attachments it is optional
    // $mail->addAttachment('/var/tmp/file.tar.gz');         
    // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');

    // Set email format to HTML if you want to send html document 
      $mail->isHTML(true);
      
    // set subject of your email
      $mail->Subject = 'Here is the subject';
     
    // write your body content we can use html    
      $mail->Body    = 'This is the HTML message body in bold!';
      $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

     

    /* finally send an email if the email send is a success then print ‘Message has been sent’
      if not then print 'Message could not be sent'
    */
      if(!$mail->send()) {
       echo 'Message could not be sent.';
       echo 'Mailer Error: ' . $mail->ErrorInfo;
      }  
      else  
      {
       echo ‘Message has been sen’t;
      }
      
      //Here we can change value dynamically with php variable as required
      ?>
     #Code End

    To send an email create a file sendmail.php which is located just outside of phpmailer folder. Copy these code and paste them into sendmail.php before running sendmail.php read the comment in the coding and edit it where required after saving the file, run it in your localhost server. now step 2 is completed. When we run file sendmail.php definitely we get an error which we need  to fix so we follow step 3

     

     step 3. Fix the error 

    when we run sendmail.php then often we got errors like

    • SMTP ERROR: Password command failed:
    • SMTP Error: Could not authenticate.
    • SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
    • The message could not be sent. Mailer Error: SMTP connect() failed.https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting 


     

    Don't worry there is no error in our code this error show because smtp.gmail.com is only not allowing us to send an email to the outside server(example-localhost). Gmail detects it as a less secure app. so we have to enable our Gmail account for a less secure app.

    login to your Gmail account which is the sender's Gmail in your code. try the following link  https://myaccount.google.com/u/0/lesssecureapps

    and turn on 'allow less secure app'  

    google account enable for less secure app

    But we still get the same error due to Google detecting unknown devices as our web server and restricting it so we have to fix this error manually 

    go to Google account https://myaccount.google.com/ click on sign-in & security ->click on get started under security checkup -> click on recent security events check on yes.

    enable yes for unknown devices in google acount

     

    Now we do not get any errors and our email is sent successfully by getting the message "message has been sent" If we still get errors then it may be possible two-step verification so please turn off two-step verification now our step 3 is completed. finally, run the sendphpmail.php file.

    Thanks for coming to the bottom line we hope you enjoy this method for sending emails if you still get errors then please leave a comment I respond spontaneously 

    Thanks.
     

     

    Up 0 | Down