Gmail php mail settings

Отправка писем по SMTP через Gmail

Для отправки писем по SMTP из PHP можно использовать довольно популярный php-класс, размещенный на GitHub: PHPMailer .

Рекомендуемый способ его инсталляции — через Composer (должен быть загружен или установлен на сервере). Для тестирования скрипта нужно зайти по SSH в пустой, доступный из web каталог и выполнить:

После выполнения команды в каталоге будет создана директория vendor, в которую будут загружены файлы класса PHPMailer и автозагрузчик Composer. Теперь в той же директории, из которой запускался Composer создается тестовый скрипт:

use PHPMailer\PHPMailer\PHPMailer ;
use PHPMailer\PHPMailer\Exception ;

$mail = new PHPMailer ( true ) ; // Passing `true` enables exceptions
try {
//Server settings
$mail -> setLanguage ( ‘ru’ , ‘vendor/phpmailer/phpmailer/language/’ ) ; // Перевод на русский язык

//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail -> SMTPDebug = 1 ; // Enable verbose debug output

$mail -> isSMTP ( ) ; // Set mailer to use SMTP

$mail -> SMTPAuth = true ; // Enable SMTP authentication

//$mail->SMTPSecure = ‘ssl’; // secure transfer enabled REQUIRED for Gmail
//$mail->Port = 465; // TCP port to connect to
$mail -> SMTPSecure = ‘tls’ ; // Enable TLS encryption, `ssl` also accepted
$mail -> Port = 587 ; // TCP port to connect to

$mail -> Host = ‘smtp.gmail.com’ ; // Specify main and backup SMTP servers
$mail -> Username = ‘USERNAME@gmail.com’ ; // SMTP username
$mail -> Password = ‘PASSWORD’ ; // SMTP password

//Recipients
$mail -> setFrom ( ‘USERNAME@gmail.com’ , ‘USERNAME’ ) ;
$mail -> addAddress ( ‘SENDER@example.com’ ) ; // Name is optional

//Content
$mail -> isHTML ( true ) ; // Set email format to HTML
$mail -> Subject = ‘Test mail to user’ ;
$mail -> Body = ‘This is the very simple HTML message body in bold!‘ ;
$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.’ ;
echo ‘Mailer Error: ‘ . $mail -> ErrorInfo ;
}

Еще один пример тестового скрипта: gmail.phps .

Если после запуска скрипта отображается такая ошибка: SMTP Error: Could not connect to SMTP host или SMTP ERROR: Failed to connect to server: Network is unreachable, то следует проверить открыт ли SMTP порт в firewall и работоспособность DNS-сервера. Дополнительные сведения по ошибкам находятся на этой странице: github.com/PHPMailer/PHPMailer/wiki/Troubleshooting .

Читайте также:  Функция двойного факториала питон

Настройка аккаунта Google для отправки через SMTP

Чтобы Google разрешил отправку писем через SMTP нужно произвести настройку учетной записи, иначе в логе PHPMailer может появится сообщение об ошибке: «SMTP ERROR: Password command failed: 534-5.7.14 Please log in via your web browser and then try again» (свойство $mail->SMTPDebug должно быть установлено в 1 или 2).

  • Включить доступ для менее безопасных устройств (именно такими Гугл считает сторонние SMTP сервера) по ссылке: myaccount.google.com . Также письмо со ссылкой на изменение этой настройки придет после первого безрезультатного подключения.
  • Просмотреть недавно используемые устройства: security.google.com .
  • Также может помочь эта ссылка: accounts.google.com .

Следует учитывать, что Google разрешает отправлять через свои почтовые аккаунты Gmail не более 99 писем в сутки или до 2000 (500 — пробный аккаунт), с использованием платной версии почтового приложения G Suite. При превышении ограничения на отправку писем по SMTP пользователь теряет возможность отправлять новые письма на 24 часа, но доступ к своему аккаунту остается. Поскольку правила могут измениться в будущем, то посмотреть ограничения можно на support.google.com .

Google будет автоматически изменять поле «От» любого сообщения, отправленного через SMTP на адрес электронной почты, записанный в настройках аккаунта. Чтобы изменить адрес «от» в настройках аккаунта нужно перейти на вкладку «Аккаунты и импорт» и нажать на «Добавить другой адрес электронной почты», после чего назначить его используемым по умолчанию.

Источник

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.

Читайте также:  To-do CRUD

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 .

Читайте также:  Array to object php laravel

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.

Источник

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