Php mail smtp linux

Php mail smtp linux

The behaviour of these functions is affected by settings in php.ini .

Mail configuration options

Name Default Changeable Changelog
mail.add_x_header «0» PHP_INI_PERDIR
mail.log NULL PHP_INI_SYSTEM|PHP_INI_PERDIR
mail.force_extra_parameters NULL PHP_INI_SYSTEM|PHP_INI_PERDIR
SMTP «localhost» PHP_INI_ALL
smtp_port «25» PHP_INI_ALL
sendmail_from NULL PHP_INI_ALL
sendmail_path «/usr/sbin/sendmail -t -i» PHP_INI_SYSTEM

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here’s a short explanation of the configuration directives.

Add X-PHP-Originating-Script that will include UID of the script followed by the filename.

The path to a log file that will log all mail() calls. Log entries include the full path of the script, line number, To address and headers.

Force the addition of the specified parameters to be passed as extra parameters to the sendmail binary. These parameters will always replace the value of the 5th parameter to mail() .

Used under Windows only: host name or IP address of the SMTP server PHP should use for mail sent with the mail() function.

Used under Windows only: Number of the port to connect to the server specified with the SMTP setting when sending mail with mail() ; defaults to 25.

Which «From:» mail address should be used in mail sent directly via SMTP (Windows only). This directive also sets the «Return-Path:» header.

Where the sendmail program can be found, usually /usr/sbin/sendmail or /usr/lib/sendmail . configure does an honest attempt of locating this one for you and set a default, but if it fails, you can set it here.

Systems not using sendmail should set this directive to the sendmail wrapper/replacement their mail system offers, if any. For example, » Qmail users can normally set it to /var/qmail/bin/sendmail or /var/qmail/bin/qmail-inject .

qmail-inject does not require any option to process mail correctly.

This directive works also under Windows. If set, smtp , smtp_port and sendmail_from are ignored and the specified command is executed.

User Contributed Notes 8 notes

On Ubuntu 13.04, not sure of the other Distros.

If you simply uncomment the default:

sendmail_path = «sendmail -t -i»

Your mail() functions will all fail. This is because, you should place the FULL PATH (i.e. /usr/sbin/sendmail -t -i )

The documentation states PHP tries it’s best to find the correct sendmail path, but it clearly failed for me.

So, always enter in the FULLPATH to sendmail or you may get unexpected failing results.

As a secondary note: Those that just want to ENFORCE the -f parameter, you can do so in php.ini using:

You can leave the sendmail path commented out, it will still use the defaults (under UNIX -t -i options which if you look them up are very important to have set).

Читайте также:  Php три первых символа

But, now there is no way to change this, even with the 5th argument of the mail() function. -f is important, because if NOT set, will be set to which ever user the PHP script is running under, and you may not want that.

Also, -f sets the Return-Path: header which is used as the Bounce address, if errors occur, so you can process them. You you can not set Return-Path: in mail() headers for some reason. you could before. Now you have to use the -f option.

The documentation should be made clear that sendmail does NOT default to -t -i when using just /usr/sbin/sendmail. You literally need to specify the options.

I know this might seem like a no-brainer but I wasted hours trying to get mail() to work only to discover that the sendmail program is NOT passed -t and -i by default as stipulated in the documentation.

If anyone gets this cryptic error message in the PHP error logs:
«sh: -t: command not found»
after upgrading from PHP 5.4, this may be the solution for you.

I upgraded PHP from 5.4 to 5.6 and all our mail() functionality suddenly broke, with no useful error logging.

If this is you, and you’ve been using ini_set() to set the «sendmail_path» then note that even though it’s apparently not mentioned in the upgrade documentation — or anywhere else I could find on php.net (or a dozen forums) — you’ll now need to go set the sendmail_path in your php.ini file; it is now ignored if you use ini_set() to specify a path to the sendmail binary on the fly.

So, just specify «sendmail_path» in php.ini instead. That’s all there is to it — that fixed all the mail() functionality for us.

Hope this little note saves someone else as much time as I spent troubleshooting and researching. Cheers!

It is worth reiterating that, as stated above, sendmail_path also works for Windows, overriding other Windows SMTP settings.

The comment in php.ini, “For Unix only”, does not make that clear.

This makes it relatively easy to substitute a fake sendmail program or even a shell script/batch file to save mail to a text file.

I use this technique when teaching or testing in PHP.

For linux you can over-ride the default «From» for the outgoing emails by including in php.ini this line:

sendmail_path = «/usr/sbin/sendmail -t -i -f fromMe@blah.com»

The path should work for most linux installations.

Return-path header does not work because it is not part of smtp.

on *nix -f may be set on the mail command
alternatively
some MTAs accept mbox-style «From » header on the first header line
note: no colon after «From» , must be the first header line
or you may be able to re-configure you MTA to interpret return-path headers

Читайте также:  Тег IMG, атрибут src

-f is the most reliable method but it may mean that you can’t set any other command-line option due to shell escaping problems.

also note that email formatting requirements differ between windows and everything else. sendmail expects only \n line-endings

On Darwin OS such as OSX (current one: 10.8.3) you need to add a specific command and option to the sendmail_path constant if you have downloaded and installed a mamp with a stack.

Indeed you can see the required libraries for PHP, Apache, MySQL in «common/lib» folder. The problem is when you run an external command using these libraries, for example «sendmail». It could be a problem if it gets the stack libraries and not the system ones (different versions, etc).

The «env -i» command clean the Stack environment variables and run «sendmail» with the system libraries.

Ненавижу всякие денверы и ёбн серверы.

У меня голый апач на винде 10 и на нем 6 версий пхп от 5.6 до самой последней. 🙂
Все устанавливается и конфигиться за минуты. 🙂
Все версии пхп конфигяться отдельно и работают одновременно. На разных виртуальных хостах и портах.
Не надо ничего переключать и перезапускать.

У меня еще есть виртуальная машина(WmVare) c FreeBSD 13.
Там, например, Redis.
С пхп на винде все работает.

Так вот вопрос:
можно ли юзать sendmail с виртуальной машины на юниксе
в пхп на винде?
Было бы замечательно.

Зы в идеале хочу перенести апач с пхпями на виртуальную машину с юникс.
А загружать пхп скрипты с браузера под виндой.
Там уже установлен апач и последняя версия пхп.
И еще perl и Go. (Зачем не знаю. 🙂 Было по приколу поковырять конфиги и понастраивать 🙂 )

Но пока не разобрался как в юниксах подтянуть к голому апачу несколько версий пхп. 🙁

Источник

Ubuntu — любимая ОС

Основная задача этого блога, показать как работать в Ubuntu комфортно и с удовольствием!

Отправка почты средствами php-функции mail в Ubuntu/Debian

Итак, задача: настроить на локальном сервере, под управлением ОС Ubuntu отправку почты стредствами php-функции mail().

1. Установка SendMail из репозитория Ubuntu

sudo apt-get install sendmail
# telnet localhost smtp
Trying ::1. Trying 127.0.0.1. Connected to localhost. Escape character is '^]'. 220 localhost6.localdomain6 ESMTP Sendmail 8.14.3/8.14.3/Debian-9.2ubuntu1; Thu, 9 Dec 2010 15:31:17 +0200; (No UCE/UBE) logging access from: localhost.localdomain(OK)- localhost.localdomain [127.0.0.1]
250 localhost6.localdomain6 Hello localhost.localdomain [127.0.0.1], pleased to meet you
MAIL FROM: no-reply@gmail.com
250 2.1.0 no-reply@gmail.com. Sender ok
250 2.1.5 my_exist@gmail.com. Recipient ok
354 Enter mail, end with "." on a line by itself
250 2.0.0 oB9DVHsE004837 Message accepted for delivery

В результате выполнения последовательности комманд на указанный емейл (my_exist@gmail.com) должно прийти сообщение («test message»).

gedit /etc/php5/apache2/php.ini 

Находим и редактируем следующую строчку

sendmail_path = /usr/sbin/sendmail -t -i
echo mail ("my_exist@gmail.com","test message", "test message","From:no-reply@gmail.com"); ?>

Для debian установка такая:

Читайте также:  Php check if english

Необязательно, но желательно — обновляем репозиториум командой: apt-get update

Затем ставим sendmail командой: apt-get install sendmail-bin

‘+relatedpoststitle+’

14 комментариев: Leave Your Comments

Добрый день есть проблема в вожу HELO localhost выдает ошибку,
500 5.5.1 Command unrecognized: «HELLO localhost»

не подскажите как можно решить ? Ответить Удалить

посмотрите здесь: http://forums.webscript.ru/showthread.php?s=f62585d6f95ca41bebbaf2e48437aece&postid=149689 Ответить Удалить

421 4.3.0 collect: Cannot write ./dfq3CIMoh1007381 (bfcommit, uid=0, gid=113): No such file or directory
Connection closed by foreign host.
на «test message
. «
Почему так? Ответить Удалить

Помогла перезагрузка.. почему теперь он пишет что всё отправлено (250 2.0.0 q3CInuYY001545 Message accepted for delivery), но сообщение не доходит? Удалить

Через smtp все шлет через консоль. но mail() не работает. точнее работает но не отдает по факту отправки true и по итогу получаю 504 от сервера Ответить Удалить

После того как я выполнил второй пункт статьи все прошло нормально без ошибок..но проблема в том что не доходят письма на почту..это связано с тем что я сижу под VirtualBox?Если нет то в чем проблема и как её решить! Ответить Удалить

установил sendmail
sudo apt-get install sendmail
в терминале ввёл telnet localhost smtp
выдало
Trying 127.0.0.1.
Connected to localhost.
Escape character is ‘^]’.
220 localhost.localdomain ESMTP Sendmail 8.14.4/8.14.4/Debian-2ubuntu2; Sat, 10 Nov 2012 01:15:46 +0200; (No UCE/UBE) logging access from: localhost(OK)-localhost [127.0.0.1]HELO localhost
500 5.5.1 Command unrecognized: «P PHELO localhost»

как исправить или что я сделал не так? Ответить Удалить

Здравствуйте! Делаю настройку на локальном LAMP Ubuntu 16.04 LTS по Вашей инструкции. Адрес получателя my_exist@gmail.com заменил на свой (тоже gmail.com). После ввода команды # test message
Terminal не выдает никаких сообщений. Просто мигает курсор. Письмо не приходит. Что нужно делать дальше? Ответить Удалить

У меня вот последние строчки выдаются и все на том, почта не приходит
— 250 2.0.0 vBRGYmr2006713 Message accepted for delivery
— Connection closed by foreign host. (эта строчка — после длительного ожидания)

VarangaOfficial — информация о препарате от грибка варанга — самая большая и исчерпывающа подборка фактов. Воспользовавшись данным ресурсом, вы сможете узнать полную информацию касающуюся представленного средства. Лично увидеть данные о клиническом тестировании геля, прочитать реальные отзывы пользователей и медицинского персонала. Изучить инструкцию по применению, прочитать об особенностях и методах работы комплекса, уяснить, как работает крем Варанга, где можно заказать оригинальный сертифицированный препарат и, как избежать покупки подделки. Мы очень тщательно и скурпулезно проверяем размещаемые на сайте данные. Предоставляем нашим пользователям сведения, взятые только из достоверных источников. Если вы обнаружили у себя признаки грибкового поражения стоп или уже довольно продолжительное время, без ощутимых результатов стараетесь излечиться от этого коварного, неприятного недуга, наш сайт покажет вам легкий и быстрый способ решения проблемы. Присоединяетесь и живите полноценной, здоровой жизнью. Теперь все ответы можно отыскать на одном сайте. Ответить Удалить

Источник

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