Simple Mail

How to configure PHP to send e-mail?

I need to send mail to the users of my website using php script. I have tried using mail function in php.
My code is as follows:

 $to = "myweb@gmail.com"; $subject = "Test mail"; $message = "My message"; $from = "webp@gmail.com"; $headers = "From:" . $from; mail($to,$subject,$message,$headers); 
 Warning: mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set(). 

Please tell me what address to include in the $from variable. Do I need a smtp server for this? How do I send mails using a localhost? Please tell me what exactly to edit in the php.ini file I am new to all this.. Please help me..

I take it you’re on a Windows box? You’ll need to, as specified in the error message, define your SMTP server’s address and port #. You’re trying to connect to a local SMTP server, which you do not have.

Just thought i would mention XAMPP can use mailtodisk that works well on localhost for development

8 Answers 8

require('./PHPMailer/class.phpmailer.php'); $mail=new PHPMailer(); $mail->CharSet = 'UTF-8'; $body = 'This is the message'; $mail->IsSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPSecure = 'tls'; $mail->Port = 587; $mail->SMTPDebug = 1; $mail->SMTPAuth = true; $mail->Username = 'me.sender@gmail.com'; $mail->Password = '123!@#'; $mail->SetFrom('me.sender@gmail.com', $name); $mail->AddReplyTo('no-reply@mycomp.com','no-reply'); $mail->Subject = 'subject'; $mail->MsgHTML($body); $mail->AddAddress('abc1@gmail.com', 'title1'); $mail->AddAddress('abc2@gmail.com', 'title2'); /* . */ $mail->AddAttachment($fileName); $mail->send(); 

You need to have a smtp service setup in your local machine in order to send emails. There are many available freely just search on google.

If you own a server or VPS upload the script and it will work fine.

You won’t be able to send a message through other people mail servers. Check with your host provider how to send emails. Try to send an email from your server without PHP, you can use any email client like Outook. Just after it works, try to configure PHP.ini with your email client SMTP (sending e-mail) configuration.

Here’s the link that gives me the answer and we use gmail:

Install the «fake sendmail for windows». If you are not using XAMPP you can download it here: http://glob.com.au/sendmail/sendmail.zip

Modify the php.ini file to use it (commented out the other lines):

mail function

SMTP = smtp.gmail.com smtp_port = 25 For Win32 only. sendmail_from = @gmail.com 

You may supply arguments as well (default: sendmail -t -i ).

sendmail_path = "C:\xampp\sendmail\sendmail.exe -t" 

(ignore the «Unix only» bit, since we actually are using sendmail)

Читайте также:  Статические переменные в kotlin

You then have to configure the «sendmail.ini» file in the directory where sendmail was installed:

sendmail

smtp_server=smtp.gmail.com smtp_port=25 error_logfile=error.log debug_logfile=debug.log auth_username= auth_password= force_sender=@gmail.com 

configure your php.ini like this

SMTP = smtp.gmail.com [mail function] ; XAMPP: Comment out this if you want to work with an SMTP Server like Mercury ; SMTP = smtp.gmail.com ; smtp_port = 465 ; For Win32 only. ; http://php.net/sendmail-from ;sendmail_from = postmaster@localhost 

To fix this, you must review your PHP.INI, and the mail services setup you have in your server.

But my best advice for you is to forget about the mail() function. It depends on PHP.INI settings, it’s configuration is different depending on the platform (Linux or Windows), and it can’t handle SMTP authentication, which is a big trouble in current days. Too much headache.

Use «PHP Mailer» instead (https://github.com/PHPMailer/PHPMailer), it’s a PHP class available for free, and it can handle almost any SMTP server, internal or external, with or without authentication, it works exactly the same way on Linux and Windows, and it won’t depend on PHP.INI settings. It comes with many examples, it’s very powerful and easy to use.

On anything other than MSWindows it doesn’t use SMTP — so why should it implement SMTP authentication?

@symcbean Because in MANY situations you need to. PHP Mailer is just much better: it allows you to use security if you need to, but it can work without it. However, the mail() function won’t allow it in any way. So, the choice is clear. Go see, for example, what WordPress and other CMS use to send their emails: it’s PHP Mailer, and NOT mail().

I think you’re missing the point PHP is not a webserver. PHP is not an MTA. There are lots of tools to extend PHP’s functionality to support different protocols hence it DOES NOT NEED to do those things. If you want a single tool which implements everything badly then PHP is not a good choice. I have no problem with you recommending phpmailer, nor would I criticise you for suggesting a smart relay which support SSMTP / SMTP/TLS / SMTP auth / pop before SMTP. but it’s absurd to criticize PHP for not implementing functionality that is better implemented elsewhere and trivial to integrate.

Am I criticizing PHP? I’m just saying the mail() function lacks some important features, just like you did in your own answer, and I recommended a free class, written in PHP, that does everything he may ever need, just like you did, after me.

Читайте также:  Java разница list arraylist

This will not work on a local host, but uploaded on a server, this code should do the trick. Just make sure to enter your own email address for the $to line.

  

Title


Name:
'.$name.'

Email:
'.$email.'

'; //headers $headers = "From: ".$name." \r\n"; $headers = "Reply-To: ".$email."\r\n"; $headers = "MIME-Version: 1.0\r\n"; $headers = "Content-type: text/html; charset=utf-8"; //send $send = mail($to, $subject, $body, $headers); if ($send) < echo '
'; echo "Success. Thanks for Your Message."; > else < echo 'Error.'; >> ?>


Usually a good place to start when you run into problems is the manual. The page on configuring email explains that there’s a big difference between the PHP mail command running on MSWindows and on every other operating system; it’s a good idea when posting a question to provide relevant information on how that part of your system is configured and what operating system it is running on.

Your PHP is configured to talk to an SMTP server — the default for an MSWindows machine, but either you have no MTA installed or it’s blocking connections. While for a commercial website running your own MTA robably comes quite high on the list of things to do, it is not a trivial exercise — you really need to know what you’re doing to get one configured and running securely. It would make a lot more sense in your case to use a service configured and managed by someone else.

Since you’ll be connecting to a remote MTA using a gmail address, then you should probably use Gmail’s server; you will need SMTP authenticaton and probably SSL support — neither of which are supported by the mail() function in PHP. There’s a simple example here using swiftmailer with gmail or here’s an example using phpmailer

Источник

PHP mail под Windows

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 .

Читайте также:  Display date in format php

Дело в том, что функция 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

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

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

01 02 03 04  05 06 07 Сообщение отправлено"; 15 > 16 else < 17 echo "

При отправке сообщения возникла ошибка

"; 18 > 19 > 20 ?> 21
22

23 24 25

26

27 28 29

30

31 32 33

34

35 36

37
38 39

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

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

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

Источник

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