Send via gmail php

PHPMailer using Gmail SMTP server | How-to Guide

At Bobcares, we offer solutions for every query, big and small, as a part of our Server Management Services.

Let’s take a look at how our Support Team is ready to help customers with PHPMailer using Gmail SMTP server.

How to send an email with PHPMailer using Gmail SMTP server

PHPMailer is popular over simple mail as it offers a lot of additional functionality like attachments, encryption, authentication, and so on. Furthermore, it simplifies the process of sending HTML emails.

Additionally, we don’t need to utilize a local mail server as it contains an integrated SMTP client. It’s useful for platforms that don’t have a local mail server, such as Pantheon.

Although there are other alternative options, our Support Techs recommend PHPMailer over them. Today, we are going to take a look at how we can use PHPMailer to send emails via Gmail SMTP.

Before we proceed, here are a few of the limitations of Gmail SMTP servers and how to deal with them:

  • The number of recipients in a single email and the number of emails that can be sent each day are set to 500 emails and 500 recipients respectively in Gmail. There is no way to exceed this restriction. However, we can send more than these limits, by using a third-party email distribution platform.
Читайте также:  Проверка поддержки браузером javascript

How to enable Third-party Apps/Code Email Sending in Gmail

How to install PHPMailer

Our Support Techs offer two ways to install PHPMailer:

composer require phpmailer/phpmailer

Alternatively, we can also download PHPMailer from this link and copy the contents of the folder to one of the PHP configuration’s include_path directories.

After that, add the following code to the PHP file to manually load each class file:

use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception;
require 'path/to/PHPMailer/src/Exception.php'; require 'path/to/PHPMailer/src/PHPMailer.php'; require 'path/to/PHPMailer/src/SMTP.php';

Sample PHP code to send email via Gmail SMTP

Here is the code we need to add to the PHP file via which we want to send the email. Our Support Techs would like to point out that we have to change the values as per our domain and usernames.

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

$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->Mailer = “smtp”;

try $mail->SMTPDebug = 1;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = “tls”;
$mail->Port = 587;
$mail->Host = “smtp.gmail.com”;
$mail->Username = “your-email@gmail.com”;
$mail->Password = “your-gmail-password”;

//Recipients
$mail->IsHTML(true);
$mail->AddAddress(“recipient@domain”, “recipient-name”);
$mail->SetFrom(“from@gmail.com”, “from-name”);
$mail->AddReplyTo(“reply-to@domain”, “reply-to-name”);
$mail->AddCC(“cc-recipient@domain”, “cc-recipient-name”);
$mail->Subject = “Test Email sent via Gmail SMTP Server using PHP Mailer”;
$content = “This is a Test Email sent via Gmail SMTP Server using PHP mailer class.”;

//Attachments
$mail->addAttachment(‘/var/tmp/file.tar.gz’); //Add attachments
$mail->addAttachment(‘/tmp/image.jpg’, ‘new.jpg’); //Optional name

//Content
$mail->MsgHTML($content);
if(!$mail->Send()) echo “Error while sending Email.”;
var_dump($mail);
> else echo “Email sent successfully”;
>
>

With these new changes, we will be able to successfully send an email via Gmail SMTP server using PHPMailer.

[Need assistance with another query? We are available 24/7.]

Conclusion

In brief, our skilled Support Engineers at Bobcares demonstrated how to send an email with PHPMailer using Gmail SMTP server

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

2 Comments

I have been using PHPMailer for several years with a setup similar to your recommendations. Unfortunately as of 31 May 2022 Google has removed the option “Next, turn the Less Secure App setting to ON.” (Your step 3.) and since them my emails have been failing with “SMTP Error: Could not authenticate.” Are you aware of any way round it or alternative solution? Reply

Источник

How to send email from Gmail with PHP

App Passwords row

Over the last few years, Google has made changes to the way you get to use their SMTP servers to send emails. The last change was made on May 30, 2022.

This blog post shows you how to use PHP to send email from your Gmail account.

NOTE: If you want to take the easy way out, install PHPMailer and skip reading the rest of this blog post. If you want to install and use a mail server, read on.

There are three main steps in this:

  1. Write the PHP code. Our code will use the mail() function.
  2. Create an App Password from Google Permissions and Security Settings page.
  3. Configure and update Postfix

PHP mail() function

If your web runs on PHP and you want to send emails from your Gmail account, you can use PHP’s mail() function. You can either send plaintext emails or HTML emails.

This is a sample PHP code for sending email.

'; $TOEMAIL = "youremail@gmail.com"; $SUBJECT = "A simple hello"; $PLAINTEXT = "Hello from my PHP script"; $RANDOMHASH = "anyrandomhash"; $FICTIONALSERVER = "@email.myownserver.com"; $ORGANIZATION = "myownserver.com"; // Basic headers $headers = "From: ".$FROMEMAIL."\n"; $headers .= "Reply-To: ".$FROMEMAIL."\n"; $headers .= "Return-path: ".$FROMEMAIL."\n"; $headers .= "Message-ID: \n"; $headers .= "X-Mailer: Your Website\n"; $headers .= "Organization: $ORGANIZATION\n"; $headers .= "MIME-Version: 1.0\n"; // Add content type (plain text encoded in quoted printable, in this example) $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n"; // Convert plain text body to quoted printable $message = quoted_printable_encode($PLAINTEXT); // Create a BASE64 encoded subject $subject = "=?UTF-8?B?".base64_encode($SUBJECT)."?="; // Send email mail($TOEMAIL, $subject, $message, $headers, "-f".$FROMEMAIL); ?> 

We set the values for sender email, recipient email, subject and email content. That was the first part. This script will not send an email because Gmail SMTP servers have restrictions preventing it.

Less secure app is gone

Previously, Google used to allow you to enable Less secure app access. By enabling it, it would also lower the security of your Gmail account in exchange of allowing you to send email using their servers.

Google removed this on May 30th.

Less secure app access

The current and more secure way is using App Passwords.

Create App Password

In order to use the Gmail SMTP servers, we have to open Google Security page page.

Enable 2-Step Verification if you have not already enabled it.

Once you have enabled 2-Step Verification, you will notice a new row called App Passwords.

App Passwords row

Click on App Passwords and generate a new App Password. You should get something like this. Note it down.

Generate App Password

Write it down or copy paste the app password in the yellow box.

Go back to the App Passwords page to make sure it has been created.

App Password created

Now that the App Password creation has been successful, let us install a mail server. I prefer Postfix because it is easy to set up and very configurable.

Install Postfix mail server

Install Postfix on your server.

If you use Debian or Ubuntu, run this:

On CentOS or RedHat, run this:

Configure Postfix to hold App Password

We will store the email and app password in the mail server configuration setting. This is a comparatively higher level of security than the alternative, which is storing the password in your code (which I will not recommend).

Edit /etc/postfix/main.cf and include these lines at the bottom of the file:

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination myhostname = email.myownserver.com # Change this to your own server name alias_maps = hash:/etc/aliases alias_database = hash:/etc/aliases myorigin = /etc/mailname mydestination = $myhostname, email.myownserver.com, localhost relayhost = [smtp.gmail.com]:587 mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 mailbox_size_limit = 0 recipient_delimiter = + inet_interfaces = all inet_protocols = all # Enable SASL authentication smtp_sasl_auth_enable = yes # Disallow methods that allow anonymous authentication smtp_sasl_security_options = noanonymous # Location of sasl_passwd smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd # Enable STARTTLS encryption smtp_tls_security_level = encrypt # Location of CA certificates smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt 

Storing usernames and passwords in sasl_passwd

The app password will be stored in /etc/postfix/sasl_passwd .

Create a file /etc/postfix/sasl_passwd and add this into it.

[smtp.gmail.com]:587 arulmailer@gmail.com:yxzxijpgcgerxzqa 

Remember to put in your own Gmail address and app password instead of copy-pasting the above.

Finally, to make this plaintext file secure, chown it to root:root and change permission to 0600 as root.

sudo chown root:root /etc/postfix/sasl_passwd sudo chmod 0600 /etc/postfix/sasl_passwd

Create a hash database file for Postfix using postmap . A new file named sasl_passwd.db is created at /etc/postfix/sasl_passwd.db .

sudo postmap /etc/postfix/sasl_passwd

Test Postfix from command line and PHP script

To test if Postfix configuration is correct, try sending a hello email from the command line:

echo "Hello Postfix" | mail -s "Postfix configured" -a "From:arulmailer@gmail.com" youremail@gmail.com

Check whether you have received this email that says «Postfix configured» with body «Hello Postfix».

If successful, then run the PHP script and see if the PHP script has sent the email successfully.

Point to note

Google is strict on how many emails are sent at once and they do have a limit of 500 emails per day. If you are looking at mass emailing customers, then you may want to consider a paid email marketing solution.

For most hobbyists and amateurs, this should be a good solution as of June 2022.

Has this worked for you?

If this tutorial has worked for you, please let me know, and share this post. You can also let me know if you are unable to set it up.

If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom . You can also post questions in our Facebook group. Thank you.

Disclaimer: Our website is supported by our users. We sometimes earn affiliate links when you click through the affiliate links on our website.

My name is Arul and I work as a software engineer at NASA. This website consists of a collection of tools, utilities and articles I wrote over the last 22 years. The Articles section covers a variety of areas from technical to aquarium topics. You will also find free APIs that you can use in your applications.

Источник

Оцените статью