Php ini mail windows

Runtime Configuration

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

Mail configuration options

Name Default Changeable Changelog
mail.add_x_header «0» INI_PERDIR  
mail.mixed_lf_and_crlf «0» INI_SYSTEM|INI_PERDIR Added in PHP 8.2.4
mail.log NULL INI_SYSTEM|INI_PERDIR  
mail.force_extra_parameters NULL INI_SYSTEM  
SMTP «localhost» INI_ALL  
smtp_port «25» INI_ALL  
sendmail_from NULL INI_ALL  
sendmail_path «/usr/sbin/sendmail -t -i» INI_SYSTEM  

For further details and definitions of the
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.

mail.log
string

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.

mail.mixed_lf_and_crlf
bool

Allows reverting the line separator for email headers and message bodies to LF (Line Feed),
mimicking the non-compliant behavior of PHP 7. It is provided as a compatibility measure
for certain non-compliant Mail Transfer Agents (MTAs) that fail to correctly process CRLF
(Carriage Return + Line Feed) as a line separator in email headers and message content.

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().


In addition to the default behavior for INI_SYSTEM,
this value can also be set with php_value
in httpd.conf (but this is not recommended).

SMTP
string

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

smtp_port
int

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.

sendmail_from
string

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

sendmail_path
string

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.

Found A Problem?

elitescripts2000 at yahoo dot com

11 years ago

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:

mail.force_extra_parameters = -fdo_not_reply@domain.tld

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)....

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.

jscholz at wisc dot edu

2 years ago

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.

php dot net at ii0 dot net

8 years ago

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!

PHP mail картинка с конвертом

В этой статье я хочу рассказать об отправке почты из php скриптов под Windows.

Америку я, конечно, не открою, но надеюсь, что кому-то эта статья будет полезна или просто сэкономит время.

С точки зрения php программиста отправка почты выполняется с помощью стандартной функции mail(). И вот тут у многих начинающих разработчиков возникает проблема. Скрипт, прекрасно работающий на сервере хостера, выдает ошибки на локальном компьютере.

Обычно эти ошибки имеют примерно такое описание:
Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in E:\www\simplemail\mailer.php on line ......

Дело в том, что функция mail сама по себе почту не отправляет, она просто вызывает программу sendmail, которая в дистрибутив web сервера и php интерпретатора не входит (и не должна).

Sendmail, в свою очередь, для отправки почты использует SMTP сервер.

Таким образом, чтобы php скрипт мог отправлять почту нужно установить и настроить sendmail и SMTP сервер.

Версию sendmail для Windows можно скачать здесь.

Установка и настройка выполняется в три этапа.

1) Распаковываем архив на тот же диск, где установлен php. Например, я создал папку C:\wamp\sendmail.

2) Вносим изменения в файл php.ini:

[mail function]
SMTP =
sendmail_from =
sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

Как видите, нужно только указать путь к sendmail чтобы php мог ее найти.

3) Настраиваем sendmail. Все настройки находятся в файле sendmail.ini (расположен в папке с sendmail).

Но перед тем как приступать к настройке пару слов об SMTP сервере. Вам совсем не обязательно устанавливать сервер на вашем компьютере. Многие почтовые сервисы предоставляют бесплатный доступ к своим серверам.

Ниже я покажу пример настройки sendmail для работы с SMTP сервером mail.ru, но, естественно, вы выбрать любой другой.

Итак, открываем sendmail.ini и устанавливаем следующие параметры:

smtp_server=smtp.mail.ru; адрес SMTP сервера
smtp_port=25; порт SMTP сервера

default_domain=mail.ru; домен по-умолчанию

error_logfile=error.log; файл в который будет записываться лог ошибок

debug_logfile=debug.log; очень полезная на этапе отладки опция. Протоколируются все операции, которые выполняет sendmail

auth_username=account_name@mail.ru; имя вашего аккаунта
auth_password=account_password; ваш пароль

; следующие три опции используются если перед авторизацией на SMTP сервере требуется авторизация на POP3 сервере
pop3_server=pop.mail.ru
pop3_username=account_name@mail.ru
pop3_password=account_password

; параметр для команды MAIL FROM
force_sender=account_name@mail.ru

hostname=mail.ru

Теперь не забудьте перезапустить web сервер, чтобы изменения вступили в силу.

Чтобы протестировать работу почты напишем простенький скрипт:

01 <html xmlns="http://www.w3.org/1999/xhtml">
02 <head>
03 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
04 <title>Simple Mail</title>
05 </head>
06 <body>
07 <?php
08 $addr = $_POST['addr'];
09 $theme = $_POST['theme'];
10 $text = $_POST['text'];
11 if (isset($addr) && isset($theme) && isset($text)
12 		&& $addr != "" && $theme != "" && $text != "") {
13 	if (mail($addr, $theme, $text, "From: vova_33@mail.ru")) {
14 		echo "<h3>Сообщение отправлено</h3>";
15 	}
16 	else {
17 		echo "<h3>При отправке сообщения возникла ошибка</h3>";
18 	}
19 }
20 ?>
21 <form action="mailer.php" method="post">
22 <p>
23 	<label for="addr">eMail:</label>
24 	<input type="text" name="addr" id="addr" size="30" />
25 </p>
26 <p>
27 	<label for="theme">Тема письма:</label>
28 	<input type="text" name="theme" id="theme" size="30" />
29 </p>
30 <p>
31 	<label for="text">Текст письма:</label>
32 	<textarea rows="10" cols="20" name="text" id="text"></textarea>
33 </p>
34 <p>
35 	<input type="submit" value="Отправить" />
36 </p>
37 </form>
38 </body>
39 </html>

Он создает форму с тремя полями для ввода адреса, темы и содержания письма. Нажатие на кнопку «Отправить» отправит запрос этому же скрипту (строка 21).

Если данные введены, то будет вызвана функция mail (строка 13), которая и отправит письмо. В случае успешной отправки функция возвращает true, в противном случае — false.

Как видите, ничего сложного в настойке почты нет.

Удачи!

Источник: кросспостинг из моего блога – www.simplecoding.org.

<?php

  // обязательные переменные // важно

  $from = $_REQUEST[«from»];

  $emaila = $_REQUEST[«emaila»];

  $filea = $_REQUEST[«filea»];

  if ($filea) {

     function mail_attachment ($from , $to, $subject, $message, $attachment){

        $fileatt = $attachment; // путь к файлу

        $fileatt_type = «application/octet-stream»; // тип файла

        $start = strrpos($attachment, ‘/’) == 1 ?

           strrpos($attachment, ‘//’) : strrpos($attachment, ‘/’)+1;

        $fileatt_name = substr($attachment, $start,

           strlen($attachment)); // имя файла который используется для файла                             вложения    

        $email_from = $from; // отправитель электронного письма

        $subject = «New Attachment Message»;

        $email_subject =  $subject; // тема электронного письма

        $email_txt = $message; // содержимое электронного письма

        $email_to = $to; // получатель электронного письма

        $headers = «From: «.$email_from;

        $file = fopen($fileatt,‘rb’);

        $data = fread($file,filesize($fileatt));

        fclose($file);

        $msg_txt=«\n\n You have recieved a new attachment message from $from»;

        $semi_rand = md5(time());

        $mime_boundary = «==Multipart_Boundary_x{$semi_rand}x»;

        $headers .= «\nMIME-Version: 1.0\n» . «Content-Type: multipart/mixed;\n» . «

           boundary=\»{$mime_boundary}\»»;

        $email_txt .= $msg_txt;

        $email_message .= «This is a multi-part message in MIME format.\n\n» .

           «—{$mime_boundary}\n» . «Content-Type:text/html;

           charset = \»iso-8859-1\»\n» . «Content-Transfer-Encoding: 7bit\n\n» .

           $email_txt . «\n\n»;

        $data = chunk_split(base64_encode($data));

        $email_message .= «—{$mime_boundary}\n» . «Content-Type: {$fileatt_type};\n» .

           » name = \»{$fileatt_name}\»\n» . //»Content-Disposition: attachment;\n» .

           //» filename = \»{$fileatt_name}\»\n» . «Content-Transfer-Encoding:

           base64\n\n» . $data . «\n\n» . «{$mime_boundary}\n«;

        $ok = mail($email_to, $email_subject, $email_message, $headers);

        if($ok) {

           echo «File Sent Successfully.«;

           unlink($attachment); // файл вложения.

        }else {

           die(«Sorry but the email could not be sent. Please go back and try again!«);

        }

     }

     move_uploaded_file($_FILES[«filea«][«tmp_name«],

        ‘temp/’.basename($_FILES[‘filea’][‘name’]));

     mail_attachment(«$from«, «youremailaddress@gmail.com«,

        «subject«, «message«, («temp/«.$_FILES[«filea«][«name«]));

  }

?>

<html>

  <head>

     <script language = «javascript» type = «text/javascript»>

        function CheckData45() {

           with(document.filepost) {

              if(filea.value ! = «») {

                 document.getElementById(‘one’).innerText =

                    «Attaching File … Please Wait»;

              }

           }

        }

     </script>

  </head>

  <body>

     <table width = «100%» height = «100%» border = «0»

        cellpadding = «0» cellspacing = «0»>

        <tr>

           <td align = «center»>

              <form name = «filepost» method = «post»

                 action = «file.php» enctype = «multipart/form-data» id = «file»>

                 <table width = «300» border = «0» cellspacing = «0»

                    cellpadding = «0»>

                    <tr valign = «bottom»>

                       <td height = «20»>Your Name:</td>

                    </tr>

                    <tr>

                       <td><input name = «from» type = «text»

                          id = «from» size = «30»></td>

                    </tr>

                    <tr valign = «bottom»>

                       <td height = «20»>Your Email Address:</td>

                    </tr>

                    <tr>

                       <td class = «frmtxt2»><input name = «emaila»

                          type = «text» id = «emaila» size = «30»></td>

                    </tr>

                    <tr>

                       <td height = «20» valign = «bottom»>Attach File:</td>

                    </tr>

                    <tr valign = «bottom»>

                       <td valign = «bottom»><input name = «filea»

                          type = «file» id = «filea» size = «16»></td>

                    </tr>

                    <tr>

                       <td height = «40» valign = «middle»><input

                          name = «Reset2» type = «reset» id = «Reset2» value = «Reset»>

                       <input name = «Submit2» type = «submit»

                          value = «Submit» onClick = «return CheckData45()»></td>

                    </tr>

                 </table>

              </form>

              <center>

                 <table width = «400»>

                    <tr>

                       <td id = «one»>

                       </td>

                    </tr>

                 </table>

              </center>

           </td>

        </tr>

     </table>

  </body>

</html>

Did you have problems setting up PHP on a Windows server that is running IIS and an SMTP server inside IIS? Have you faced problems sending mail from PHP scripts running on the IIS server with the IIS SMTP engine? By default, IIS doesn’t allow relaying SMTP emails if it comes from 3rd party products. So this problem is related to IIS SMTP “Relay Restrictions”. Sometimes some of my clients are using PHP on Windows servers using IIS 6 as the webserver. In Linux, PHP supports the native Sendmail system from the OS itself. But in windows, you need to tweak your way to make PHP able to send out mail from localhost. If you are a .Net developer, you might already know that from ASP.Net codes or even Classic ASP code, it’s just as simple as 1,2,3 to send out an email or use the IIS local SMTP server. Let me make it simple for you so that you guys can use the localhost server from PHP.

More information is at the end of the article about using XAMPP Sendmail in Windows.

Get the Best Updates on SaaS, Tech, and AI

Here is the stuff needed to do:

1. Install and Configure IIS with PHP

First, install and configure PHP 5 as described in the PHP documentation. Try to avoid the Windows-based binary installer. Download the full package and install it manually.

2. Test out PHP Pages

Once you’ve done with the installation. Test it out with a sample PHP info page. If PHP is able to execute the pages on the server then we are ready for the next step.

3. Test email sending from PHP

Now we need a test script to check whether we are able to send email using PHP. Here is a sample script that will aid you out in this situation. Copy the content from this code and save it as email_test.php at your server root. Then try to run the file online (eg. mydomain.com/email_test.php) if it returns “not ok” means you are not able to send an email out. You can change the ‘user@mydomain.com’ into your email address so that you can receive the mail if it’s a success.

Contents of email_test.php:

<?php
if(mail('user@mydomain.com','test subject','test message')){
      echo('ok');
    }
else{
      echo('not ok');
    }
?>

4. Configure PHP.INI for SMTP

Let’s stop IIS from the IIS Manager. Now open your PHP.INI file. It could be on your C:\PHP folder or C:\WINDOWS folder. Depends on how you’ve configured IIS and PHP on your system. Once you’ve opened the PHP.INI file with notepad or something, search for the entry called “[mail function]” and set it as below.

Save and close the PHP.INI file.

5. Configure IIS SMTP Relay Restrictions

Once you’re done with PHP.INI, head over to Internet Information Services Manager. Assume that the IIS is running an SMTP server also to send out emails. You should be able to see the entry inside the IIS manager stated “Default SMTP Virtual Server” or similar items. Now, right-click and access the properties page from “Default SMTP Virtual Server” as it’s shown below.

on the properties page move to “Access” tab and click on “Connection” and you will be able to see which servers/IP’s are allowed to make a connection to the server. If “127.0.0.1” IP is not there on the list, add it using the “Add” button, additionally, you may also insert your server IP on the list.

Once you are done at the “Connections” window, click on the OK button to accept the information. Now Click on the “Relay” button at the “Access” tab and set up the relay options for the server. Grant the IPs’s allowed to relay out mail for the mail server. Make sure “localhost” and IP “127.0.0.1” are granted for the relay, In addition to that, you can also insert your domain name and IP.

Once you are done with the “Relay Restrictions” window, click ok to accept the options and then click “Apply” and “Ok” buttons respectively to go back to the main screen of IIS Manager.
Now you can restart IIS from the IIS manager.

6. Try sending email again

Now for your testing run the email_test.php file again. It should give you the response “ok“. If it’s not please check your SMTP configuration one more time along with PHP server settings and PHP.INI file.


While you are here, you can also find out the information about

How to use XAMPP on windows to send mail out using PHP

You can send mail from localhost with Sendmail package, Sendmail package is inbuild in XAMPP. So if you are using XAMPP then you can easily send mail from localhost.

for example, you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for Gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for Gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = my-gmail-id@gmail.com
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with the following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
auth_username=my-gmail-id@gmail.com
auth_password=my-gmail-password
force_sender=my-gmail-id@gmail.com

Now you have done!! create a PHP file with mail function and send mail from localhost.

PS: don’t forget to replace my-gmail-id and my-gmail-password in the above code. Also, don’t forget to remove duplicate keys if you copied settings from above. For example comment following line if there is another sendmail_path : sendmail_path="C:\xampp\mailtodisk\mailtodisk.exe" in the php.ini file

Also, remember to restart the server using the XAMMP control panel so the changes take effect.

For Gmail please check https://support.google.com/accounts/answer/6010255 to allow access from less secure apps.

To send an email on Linux (with Sendmail package) through Gmail from localhost please check PHP+Ubuntu Send email using Gmail from localhost.

CREDIT: The information above is collected from StackOverflow answer.

If you would like to use PHP/MySQL/Apache from a portable drive, you can check this article.

wiki:setup_smtp_in_php_ini_with_authentication

Table of Contents

Setup SMTP Mail with Authentication in php.ini file on Windows IIS

  • Make sure that you install Notepad++ to your windows server because native Notepad Windows app won’t work for this.

  • On the Windows web server, locate the PHP installation folder. Example c:\php\

  • Open the php.ini file using Notepad++ editor (right click php.ini and left click “open with” and select Notepad++).

  • Search for, add or modify the [mail function] section of php.ini as follows:

[mail function]
; For Win32 only.
; http://php.net/smtp
; SMTP = localhost  REM-OUT 10-28-2017 INSERT NEXT LINE INSTEAD
SMTP = your.mailservername.tld

; http://php.net/smtp-port
smtp_port = 25

; REMARK - INSERT NEXT TWO LINES TO AUTHENTICATE THROUGH EXISTING EMAIL ACCOUNT ON SMTP SERVER
auth_username = mailuser@yourdomain.tld
auth_password = password_of_your_mailuser

; For Win32 only.
; http://php.net/sendmail-from  REMARK - INSERT AND UN-COMMENT NEW LINE HERE BASED ON EXAMPLE
;sendmail_from = me@example.com
sendmail_from = no_reply@yourmaildomain.tld
  • Save the php.ini file with those changes.

  • Restart the World Wide Web service – Internet Information Services

Create a PHP Test Mailer File

  • In some web folder on your php-enabled web site, create a text file named “phpmailtester.php”

  • Open that file with Notepad++ and insert the following php code, but change your test recipient’s email address.

  • Access the file from your website using any web browser.

  • Note: The page will be empty, but you should check your recipient email account to see whether the test mail arrived. Also view the headers or source code of the test email to see the route taken.

<?php
//REMARKS -sending email with the php mail() funtion
//REMARKS -THE COMMA-SEPARATED SINGLE-QUOTE 'DELIMITED' FIELDS OF THE mail() function BELOW: 
//FIELDS - mail('RECIPIENT_EMAIL','SUBJECT','BODY');
mail('recipient@somedomain.tld', 'Test Email using PHP', 'A message in the body of the test email');
?>

Download my example of phpmailtester.php file and modify it accordingly

phpmailtester.php
<?php
//REMARKS -sending email with the php mail() funtion
//REMARKS -THE COMMA-SEPARATED SINGLE-QUOTE 'DELIMITED' FIELDS OF THE mail() function BELOW: 
//FIELDS - mail('RECIPIENT_EMAIL','SUBJECT','BODY');
mail('recipient@somedomain.tld', 'Test Email using PHP', 'A message in the body of the test email');
?>
wiki/setup_smtp_in_php_ini_with_authentication.txt

· Last modified: 2017/10/28 18:45 by

127.0.0.1


Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Настройки снимка экрана windows 10
  • Аппаратное ускорение windows 10 pro
  • Фатальная ошибка windows 10
  • Как включить мышку на ноутбуке на windows 10
  • Программа для запуска старых игр на windows 11