Monday 29 January 2018

phpmailer gmail - PHP MAILER setting to send email through Gmail

PHP MAILER setting to send email through Gmail

Step 1:
Download a recent version of PHPMailer.

Step 1:
Use Following code to send an email from Gmail Account.

 
// Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load composer's autoloader
require 'vendor/autoload.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'user@example.com';                 // SMTP username
    $mail->Password = 'secret';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Email Sender
    $mail->setFrom('from@example.com', 'Mailer');

    //Recipients
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    $mail->addAddress('ellen@example.com');               // Name is optional
    $mail->addReplyTo('info@example.com', 'Information');
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');

    //Attachments (IF there is attachment then only include)
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML (true) 
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}

If you get similar to following Error
Please log in via your web browser and then try again.
5.7.14 Please log in via your web browser and then try again. 5.7.14 Learn more at 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 fr13sm3613053pdb.81

If Yes, 
whether you have "turned on 2-Step Verification" OR Google need Verification that you want to use your gmail as SMTP credential.

You can fix this in couple of minutes using below link:
https://support.google.com/mail/answer/78754

If any issue, please comment below in comment box: