Php mail remote smtp server

PHP Mail Relay via Remote smtp Server

I would install nullmailer and configure it to forward emails to your relay server. The linux distribution that you are using most likely has nullmailer packages, so that a sendmail binary (that is command line compatible) is installed in the proper place.

If you do not want to install nullmailer, it is possible to do with sendmail too. If you want, I will update the answer.

If you want to do this under sendmail, you have a number of choices:

(1) In sendmail.mc define the SMART_HOST to be your mail relay server:

define(SMART_HOST, `smtp:[relay.server]')dnl 

(3) Modify rule set 0 to do this. In sendmail.mc add the following lines:

LOCAL_RULE_0 R$* < @ $* . >$* $#esmtp $@ [relay.server] $: $1 < @ $2 . >$3 

Do not copy-paste the code snippet above since the left hand side is separated from the right hand side with tabs and not spaces.

After you are done editing sendmail.mc you need to compile sendmail.cf and restart sendmail. In Debian this is done by running sendmailconfig . In CentOS this is done by running /etc/mail/make followed by service sendmail restart .

Solution 2

Please search first, this was asked before (e.g. in How to configure php.ini with remote SMTP?).

The PHP mail() function always uses sendmail (on Linux/Unix). There is no way to change that by php.ini. That leaves two other means:

  • For a single application you can replace all calls to the mail() function with calls to an alternative library (e.g. PHPMailer).
  • As a more general solution you can configure your local sendmail (or whatever program provides the sendmail command) to do the right thing, i.e. set the domain’s mail server as a smarthost.

Toqeer

I am Linux system administrator and also can perform programming like automation stuff.

Updated on September 18, 2022

Comments

We have a php application running on Linux which sends emails to there users. Currently its setup like php.ini is configured to send via local sendmail server but we have separate mail server for our organization for this domain. I want to send the php application emails via that remote smtp server so these emails can have the correct SPF records and sign via DKIM. But I could not see such option in php.ini to specify the remote host address to forward emails to that, its for windows only. I saw some post which suggest phpMailer but I could not find how to configure that so all our php application could send via our remote SMTP.

Читайте также:  Код кнопки html css

Another nice point, under Ubuntu I prefer to remove Postfix and install mailx and configure it in ‘smarthost’ mode that forwards mail to the network’s mail server. Very little fiddling at install time when configured with ‘dpkg-reconfigure’.

Thanks for the answer, it will be better if you could put the sendmail configuration as well. I have sendmail already installed so I will just configure to forward to the relay host.

Источник

PHP Mail Not Working Not Sending (How To Fix It!)

After spending some time setting up your web server and writing up the scripts, the PHP mail function is not sending emails out as expected. Tutorials from all over the Internet show different solutions, and just what the heck is happening!? How do we fix it?

PHP mail requires a mail delivery server (SMTP) to send out emails, and there are 2 possible solutions:

  1. Install a local SMTP server.
    • Windows – Use Papercut for local testing.
    • Linux – Use sendmail or postfix, sudo apt-get install postfix .
  2. Use a remote SMTP server, simply point the SMTP settings in the php.ini file to the mail server.

That is the gist of it, but let us go through the actual steps on fixing the mail problem – Read on!

TLDR – QUICK SLIDES

Fix Mail Not Working Not Sending In PHP

TABLE OF CONTENTS

INSTALLING A LOCAL SMTP SERVER

All right, let us get started with the first solution – Installing a mail server on your own machine.

WINDOWS USERS – PAPERCUT SMTP FOR LOCAL TESTING

For Windows users, try out Papercut SMTP. Papercut is probably the fastest and fuss-free SMTP server for testing. While it can be configured to relay email out, I don’t really recommend using this for a production server.

LINUX USERS – POSTFIX OR SENDMAIL

For you guys who are on Linux, simply install Sendmail or Postfix –

sudo apt-get install postfix

But different flavors of Linux has a different package manager – YUM or RPM , just use whichever is correct.

UPDATE THE PHP.INI FILE

[mail function] SMTP=localhost smtp_port=25 ; For Win32 only. sendmail_from = doge@codeboxx.com

Finally in the php.ini file, simply ensure that SMTP is pointing to localhost . Also for the Windows users, set sendmail_from or you will get a “bad message return path” error message.

OTHER MAIL SERVERS – FOR PRODUCTION SERVERS

USING A REMOTE SMTP SERVER

Don’t want to install anything? Then use an existing SMTP server that you have access to.

POINT PHP.INI TO THE SMTP SERVER

To use an existing SMTP server, just update the php.ini file and point to the SMTP server accordingly. For example, we can actually point to the Gmail SMTP server:

[mail function] SMTP=smtp.gmail.com smtp_port=587 auth_username=YOUR-ID@gmail.com auth_password=YOUR-PASSWORD

That’s it, but I will not recommend using your personal Gmail, Yahoo, or Outlook accounts on production servers… At least use one of their business accounts.

Читайте также:  Css v34 cfg by lolyou

EXTRA – GMAIL AUTHENTICATION

Is Google rejecting the SMTP requests? Authentication failure? That is because Google will simply not allow any Tom, Dick, and Harry to access your email account. Thankfully, we only need to do some security setting stuff to get past this issue.

ENABLE 2-STEP AUTHENTICATION

Firstly, enable the 2-step authentication on your Google account if you have not already done so. That is basically, sending a PIN code to your mobile phone when Google detects login from an unknown device.

CREATE AN APP PASSWORD

But of course, we are not going to answer a PIN code challenge whenever we try to send an email from the server… So what we are going to do instead, is to create an app password.

Select “Other (Custom Name)” under the drop-down menu.

You can name it whatever you want…

DONE!

Finally, just copy that email/password into php.ini .

EXTRA BITS

That’s all for the tutorial, and here is a small section on some extras that may be useful to you.

PHP MAIL DEBUGGING

  1. In your PHP script, check the error message after sending out the email – if (!mail(TO, SUBJECT, MESSAGE)) < print_r(error_get_last()); >
  2. Set mail.log = FOLDER/mail.log in php.ini .
  3. Also, set a mail log on the SMTP server itself.

That’s all. Do a test mail send and trace the log files – Did PHP send out the email? Did the SMTP server send out the email? Are the configurations correct? Lastly, also very important – Did you send it to the correct email address, is it even a valid email?

TONE DOWN FIREWALLS, ANTI-VIRUS, CHECK SPAM FOLDER

  • Windows – Check and allow an exception in the Windows firewall.
  • Linux – Allow an exception in iptables .
  • Elsewhere – Maybe a hardware firewall that is somewhere in the network, or an anti-virus stopping the SMTP send.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped to solve your email problems, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

Источник

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

В последнее время письма отправляемые с хостингов через функции mail() и mb_send_mail() часто попадают в спам или совсем не доходят до адресатов. Альтернатива – это отправка e-mail через SMTP с реального почтового ящика.

use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require_once '/PHPMailer/src/Exception.php'; require_once '/PHPMailer/src/PHPMailer.php'; require_once '/PHPMailer/src/SMTP.php'; // Для более ранних версий PHPMailer //require_once '/PHPMailer/PHPMailerAutoload.php'; $mail = new PHPMailer; $mail->CharSet = 'UTF-8'; // Настройки SMTP $mail->isSMTP(); $mail->SMTPAuth = true; $mail->SMTPDebug = 0; $mail->Host = 'ssl://smtp.gmail.com'; $mail->Port = 465; $mail->Username = 'Логин'; $mail->Password = 'Пароль'; // От кого $mail->setFrom('mail@snipp.ru', 'Snipp.ru'); // Кому $mail->addAddress('mail@site.com', 'Иван Петров'); // Тема письма $mail->Subject = $subject; // Тело письма $body = '

«Hello, world!»

'; $mail->msgHTML($body); // Приложение $mail->addAttachment(__DIR__ . '/image.jpg'); $mail->send();

Если при отправки писем возникает ошибка « Could not connect to SMTP host », то необходимо добавить следующие строки:

$mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) );

Яндекс Почта

$mail->Host = 'ssl://smtp.yandex.ru'; $mail->Port = 465; $mail->Username = 'Логин@yandex.ru'; $mail->Password = 'Пароль';

В настройках почты нужно разрешить доступ к почтовому ящику с помощью почтовых клиентов:

Читайте также:  Who was monty python

Разрешить доступ к почтовому ящику с помощью почтовых клиентов в Яндекс почте

Mail.ru

$mail->Host = 'ssl://smtp.mail.ru'; $mail->Port = 465; $mail->Username = 'Логин@mail.ru'; $mail->Password = 'Пароль';

Gmail

$mail->Host = 'ssl://smtp.gmail.com'; $mail->Port = 465; $mail->Username = 'Логин@gmail.com'; $mail->Password = 'Пароль';

Если возникает ошибка при отправки почты, то нужно отключить двухфакторную авторизацию и разблокировать «ненадежные приложения» в настройках конфиденциальности аккаунта https://myaccount.google.com/security?pli=1

Отключить двухфакторную авторизацию Gmail

Разблокировать «ненадежные приложения» в настройках Gmail

Рамблер

$mail->Host = 'ssl://smtp.rambler.ru'; $mail->Port = 465; $mail->Username = 'Логин@rambler.ru'; $mail->Password = 'Пароль';

iCloud

$mail->Host = 'ssl://smtp.mail.me.com'; $mail->Port = 587; $mail->Username = 'Логин@icloud.com'; $mail->Password = 'Пароль';

Мастерхост

$mail->Host = 'ssl://smtp.masterhost.ru'; $mail->Port = 465; $mail->Username = 'Логин@домен.ru'; $mail->Password = 'Пароль';

Timeweb

$mail->Host = 'ssl://smtp.timeweb.ru'; $mail->Port = 465; $mail->Username = 'Логин@домен.ru'; $mail->Password = 'Пароль';

Хостинг Центр (hc.ru)

Доступ к сторонним почтовым серверам по SMTP-портам (25, 465, 587) ограничен, разрешена отправка не более 300 сообщений в сутки.

$mail->Host = 'smtp.домен.ru'; $mail->SMTPSecure = 'TLS'; $mail->Port = 25; $mail->Username = 'Логин@домен.ru'; $mail->Password = 'Пароль';

REG.RU

$mail->Host = 'ssl://serverXXX.hosting.reg.ru'; $mail->Port = 465; $mail->Username = 'Логин@домен.ru'; $mail->Password = 'Пароль';

Имя сервера на reg.ru

Имя сервера на reg.ru

ДЖИНО

У jino.ru нужно включить опцию «SMTP-сервер»

$mail->Host = 'ssl://smtp.jino.ru'; $mail->Port = 465; $mail->Username = 'Логин@домен.ru'; $mail->Password = 'Пароль';

nic.ru

$mail->Host = 'ssl://mail.nic.ru'; $mail->Port = 465; $mail->Username = 'Логин@домен.ru'; $mail->Password = 'Пароль';

Бегет — beget.com

$mail->Host = 'ssl://smtp.beget.com'; $mail->Port = 465; $mail->Username = 'Логин@домен.ru'; $mail->Password = 'Пароль';

Спринтхост — sprinthost.ru

$mail->Host = 'ssl://smtp.ВАШ_ДОМЕН'; $mail->Port = 465; $mail->Username = 'Логин@домен.ru'; $mail->Password = 'Пароль';

Источник

Отправка почты через SMTP с помощью PHP

Отправка почты через SMTP с помощью PHP на картинке

Здравствуйте дорогие читатели. В этой записи я расскажу Вам как отправить письмо с вашего сайта через SMTP сервер. Перед тем, как отправлять письма через SMTP необходимо обязательно настроить DMARC, DKIM, SPF. Если не настроить, ваши письма будут попадать в спам, но нам этого не нужно. Статья — Как настроить DMARC, SPF, DKIM подпись на своем сайте.

Готовый класс — PHP

Для начала загрузите готовый класс, по ссылке — SendMailSmtpClass.php.zip

Распаковываем архив, и размещаем в любую директорию на Вашем сайте.

Настройка класса

Настройка очень простая. Разместите этот код на странице, которая присутствует на каждой. Обычно это — страница конфига.

require_once "SendMailSmtpClass.php"; // подключаем класс //ДЛЯ YANDEX.RU $mailSMTP = new SendMailSmtpClass('mail@yandex.ru', 'pass', 'ssl://smtp.yandex.ru', 465, "UTF-8"); //ДЛЯ MAIL.RU $mailSMTP = new SendMailSmtpClass('mail@mail.ru', 'pass', 'ssl://smtp.mail.ru', 465, "UTF-8"); //РАСШИФРОВКА ЗНАЧЕНИЙ $mailSMTP = new SendMailSmtpClass('логин', 'пароль', 'хост', 'порт', 'кодировка письма');

Код отправки самого письма:

$from = array("Блог программиста", // Имя отправителя "support@212d.ru" // почта отправителя ); $result = $mailSMTP->send('Кому письмо, можно через , два получателя', 'Тема письма', 'Текст письма', $from); 

$result возвращает либо true — успешная отправка, либо false — ошибка.

Прикрепление файлов к письму

$mailSMTP->addFile("file1.jpg"); $mailSMTP->addFile("file2.jpg");

В итоге, если Вы все настроили правильно Ваше письмо будет отправляется через этот SMTP сервер с подписей DKIM, и не попадет в спам.

Пишите свои вопросы, предложения в комментариях помогу Всем!

Источник

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