Cara menggunakan php send email gmail

The author voluntarily contributed this tutorial as a part of Pepipost Write to Contribute program.

Introduction

In this tutorial, you will learn how to send email in PHP using PHPMailer library via Gmail SMTP.  Like PHPMailer, there are few more good email sending libraries in PHP e.g. PEAR::Mail interface, Swiftmailer etc which can help you easily send mail in PHP using Gmail SMTP.

Prerequisites

Before starting with steps on how to send mail using SMTP in PHP example, lets first see what are few limits with Gmail SMTP servers and how to overcome some of these:

  • Gmail limits the number of recipients in a single email and the number of emails that can be sent per day. The current limit is 500 Emails in a day or 500 recipients in a single email. You can't really increase this limit. If you want to send above these limit, then you need to integrate with third-party email delivery platform like Pepipost Sendgrid etc.
  • On reaching threshold limits, you won't be able to send messages for the next 24 hours. Once this temporary suspension period is over, the counter gets reset automatically, and the user can resume sending emails.
  • By default, any third-party apps/codes are not allowed to send emails using your Gmail account. And, hence there are few settings which need to be done at your end:

How To Enable Email Sending In Gmail?

  1. Before sending emails using the Gmail's SMTP Server, you to make some of the security and permission level settings under your Google Account Security Settings.
  2. Make sure that 2-Step-Verification is disabled.
  3. Turn ON the "Less Secure App" access or click here.
  4. If 2-step-verification is enabled, then you will have to create app password for your application or device.
  5. For security measures, Google may require you to complete this additional step while signing-in. Click here to allow access to your Google account using the new device/app.

Note: It may take an hour or more to reflect any security changes

Writing the PHP Code to Send Email using Gmail SMTP

Step 1:  Download PHPMailer library from this github link. To directly download the .zip file, use this link.

Unzip the master.zip in your application directory and run following command from your application directory.

composer require phpmailer/phpmailer

Composer is the recommended way to install PHPMailer.

Step 2: Writing the PHP Code to make an SMTP connection

  • Using your Gmail credentials, connect to host "smtp.gmail.com"
  • Click here for some more Examples and Tutorials of PHPMailer

Step 3: Include packages and files for PHPMailer and SMTP protocol:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

Step 4: Initialize PHP Mailer and set SMTP as mailing protocol:

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Mailer = "smtp";

Step 5: Set required parameters for making an SMTP connection like server, port and account credentials. SSL and TLS are both cryptographic protocols that provide authentication and data encryption between servers, machines and applications operating over a network. SSL is the predecessor to TLS.

$mail->SMTPDebug  = 1;  
$mail->SMTPAuth   = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port       = 587;
$mail->Host       = "smtp.gmail.com";
$mail->Username   = "[email protected]";
$mail->Password   = "your-gmail-password";

Step 6: Set the required parameters for email header and body:

$mail->IsHTML(true);
$mail->AddAddress("[email protected]", "recipient-name");
$mail->SetFrom("[email protected]", "from-name");
$mail->AddReplyTo("[email protected]", "reply-to-name");
$mail->AddCC("[email protected]", "cc-recipient-name");
$mail->Subject = "Test is Test Email sent via Gmail SMTP Server using PHP Mailer";
$content = "<b>This is a Test Email sent via Gmail SMTP Server using PHP mailer class.</b>";

Step 7: Send the email and catch required exceptions:

$mail->MsgHTML($content); 
if(!$mail->Send()) {
  echo "Error while sending Email.";
  var_dump($mail);
} else {
  echo "Email sent successfully";
}

Working PHP Code to Send Email Using SMTP Server

Click here to download the complete working PHP code to send email using Gmail SMTP server. You need to just change a few values and it should work.

List of Possible Errors And Exceptions

Error 1: Password Command Failed: 534-5.7.9 Application-Specific Password Required🔗

SMTP ERROR: Password command failed: 534-5.7.9 Application-specific password required. Learn more at 534 5.7.9  https://support.google.com/mail/?p=InvalidSecondFactor z2sm11041738pfq.58 - gsmtp
SMTP Error: Could not authenticate.
CLIENT -> SERVER: QUIT
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Problem sending email.

This happens mostly when SMTP Mail Server Credentials were correct but Application Specific Password was not provided.

Error 2: SMTP ERROR: Password Command Failed: 535-5.7.8 Username And Password Not Accepted🔗

SMTP ERROR: Password command failed: 535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8  https://support.google.com/mail/?p=BadCredentials f3sm5807314pgj.62 - gsmtp
SMTP Error: Could not authenticate.
CLIENT -> SERVER: QUIT
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Problem sending email.

If you have encountered this error, then this is mostly because the application specific password is incorrect.

Error 3: Invalid Address: (To): Recipient-Email🔗

Invalid address:  (to): recipient-email
Problem sending email.

If you have encountered this error, then this is mostly because the recipient email is invalid.

Error 4: SMTP: SMTP Server Does No Support Authentication🔗

authentication failure [SMTP: SMTP server does no support authentication (code: 250, response: mx.google.com at your service, [98.117.99.235] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING)]

If you have encountered this error, then this is mostly because your code does not appear to be using TLS/SSL, which is necessary to deliver mail to Google , also you should be using port 587 or 465.

Reconfirm once whether the value of $host is set as follows:

$host = "ssl://smtp.gmail.com";

Error 5: Stream_socket_client(): Unable To Connect To Smtp.Gmail.Com🔗

Error on Feb 25, 2018 11:14AM - stream_socket_client(): unable to connect to smtp.gmail.com:587 (Connection timed out) in /home/dibya/public_html/dibyasahoo/app/helpers/phpmailer/smtp.php on line 222

If you have encountered this error, then this is mostly because your server cannot connect to smtp.gmail.com on port 587. This is mostly because your hosting provider has some strict firewall rule which is blocking your server to connect to any other external server over SMTP port 587.

Error 6: SMTP Server Error: 5.5.1 Authentication Required. Learn More At 530 5.5.1🔗

SMTP server error: 5.5.1 Authentication Required. Learn more at 530 5.5.1 

If you have encountered this error, then this is mostly because you have enabled 2FA on your Gmail account or you have not enabled access to Less Secure App. Read the above prerequisites to address this problem.

Error 7: Message: Fsockopen(): Unable To Connect To Ssl://Smtp.Gmail.Com🔗

Message: fsockopen(): unable to connect to ssl://smtp.gmail.com:25 (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. )

If you have encountered this error, then this is mostly because of SSL issue. You need to enable SSL in php.ini file of your server configuration. In case you are using a XAMPP server, then please check whether it is enabled or not. You will get that in PHP info.

Error 8: Emails from PHP code going in Spam

Defintely this is not an error, but definitely a point of concern. One of the most common reason of emails landing in spam is blacklisting. You should check whether your domain or IP address is blacklisted.

Debugger step-by-step output after sending email successfully

CLIENT -> SERVER: EHLO NL616
CLIENT -> SERVER: STARTTLS
CLIENT -> SERVER: EHLO NL616
CLIENT -> SERVER: AUTH LOGIN
CLIENT -> SERVER: <credentials hidden>
CLIENT -> SERVER: <credentials hidden>
CLIENT -> SERVER: MAIL FROM:<[email protected]>
CLIENT -> SERVER: RCPT TO:<[email protected]>
CLIENT -> SERVER: RCPT TO:<[email protected]>
CLIENT -> SERVER: DATA
CLIENT -> SERVER: Date: Sun, 22 Sep 2019 05:11:15 +0000
CLIENT -> SERVER: To: recipient-name <[email protected]>
CLIENT -> SERVER: From: PHP SMTP Mailer <[email protected]>
CLIENT -> SERVER: Cc: cc-recipient-name <[email protected]>
CLIENT -> SERVER: Reply-To: reply-to-name <[email protected]>
CLIENT -> SERVER: Subject: Test email using PHP mailer
CLIENT -> SERVER: Message-ID: <[email protected]>
CLIENT -> SERVER: X-Mailer: PHPMailer 6.0.7 (https://github.com/PHPMailer/PHPMailer)
CLIENT -> SERVER: MIME-Version: 1.0
CLIENT -> SERVER: Content-Type: multipart/alternative;
CLIENT -> SERVER:  boundary="b1_UlnH3mCpHcFVNBY3Lb3PR2tVs6tvdJlu2F8g5sPN4"
CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
CLIENT -> SERVER: This is a multi-part message in MIME format.
CLIENT -> SERVER: --b1_UlnH3mCpHcFVNBY3Lb3PR2tVs6tvdJlu2F8g5sPN4
CLIENT -> SERVER: Content-Type: text/plain; charset=us-ascii
CLIENT -> SERVER: This is a test email using PHP mailer class.
CLIENT -> SERVER: --b1_UlnH3mCpHcFVNBY3Lb3PR2tVs6tvdJlu2F8g5sPN4
CLIENT -> SERVER: Content-Type: text/html; charset=us-ascii
CLIENT -> SERVER: <b>This is a test email using PHP mailer class.</b>
CLIENT -> SERVER: --b1_UlnH3mCpHcFVNBY3Lb3PR2tVs6tvdJlu2F8g5sPN4--
CLIENT -> SERVER: QUIT
email sent.

Conclusion

Hope the steps explained above were useful and you were able to successfully send mail from your Gmail SMTP server using PHP. Feel free to contribute, in case you encountered some issue which is not listed as a part of this tutorial. Use below comments section to ask/share any feedback.

<? Happy Coding ?>