Simple Mail

PHP Mail Configuration

In the previous lesson, we used mail() to send mail in PHP. That lesson assumes that your PHP installation is configured for sending mail. If your system isn’t configured for sending mail, all is not lost — you can change the configuration.

The php.ini File

The php.ini file is where you configure your PHP installation. This is the file you need to edit in order to configure PHP to send mail.

You need to ensure that the php.ini file contains details of the mail server that should be used whenever your application sends mail.

To check/change your PHP mail configuration:

  1. Open your php.ini file (if you don’t know where this is, see below)
  2. Search for the line that reads [mail function]
  3. Add/change the details of your mail server. This could be a local mail server or the mail server of your ISP.
  4. Save/close the php.ini file
  5. Restart your web server

Here’s an example of what the mail settings could look like when you first open the php.ini file:

If you’re using a UNIX based system, you will need to change the line that reads ;sendmail_path = . You will also need to remove the semicolon from the start of this line (semicolons indicate that the line is a comment). For example, sendmail_path = /usr/sbin/sendmail .

Читайте также:  Python очередь и многопоточность

If you’re using a Windows system, you should change the line that reads SMTP = localhost to include your mail server (or your ISP’s mail server). You could leave it at localhost if you’re using your own local SMTP server. If you aren’t using your own local SMTP server, you will need to enter a mail server that you have access to (such as your ISP’s mail server). For example, SMTP = mail.earthlink.net .

You should also set a default «From» email address by changing the line that reads ;sendmail_from = [email protected] . For example, sendmail_from = [email protected] .

Don’t Know Your php.ini Location or sendmail_path Path?

If you don’t know where your php.ini is, or what your sendmail_path setting should be, read on.

Your php.ini may be located here: /private/etc/php.ini . And there’s a chance that your sendmail path will be at /usr/sbin/sendmail ). Having said this, each PHP installation is different, so you should check using phpinfo() .

Fortunately, this is easy to do.

phpinfo() is used to view your PHP configuration details. You can do this by creating a .php file with the following line on it: . When you run this in your browser, you will see a full list of PHP configuration variables. Simply search for the lines that contain php.ini and sendmail_path to see the values you need to use.

Источник

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 .

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

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

Источник

PHP Mail Configuration

In the previous lesson, we used mail() to send mail in PHP. That lesson assumes that your PHP installation is configured for sending mail. If your system isn’t configured for sending mail, all is not lost — you can change the configuration.

The php.ini File

The php.ini file is where you configure your PHP installation. This is the file you need to edit in order to configure PHP to send mail.

You need to ensure that the php.ini file contains details of the mail server that should be used whenever your application sends mail.

To check/change your PHP mail configuration:

  1. Open your php.ini file (if you don’t know where this is, see below)
  2. Search for the line that reads [mail function]
  3. Add/change the details of your mail server. This could be a local mail server or the mail server of your ISP.
  4. Save/close the php.ini file
  5. Restart your web server

Here’s an example of what the mail settings could look like when you first open the php.ini file:

If you’re using a UNIX based system, you will need to change the line that reads ;sendmail_path = . You will also need to remove the semicolon from the start of this line (semicolons indicate that the line is a comment). For example, sendmail_path = /usr/sbin/sendmail .

If you’re using a Windows system, you should change the line that reads SMTP = localhost to include your mail server (or your ISP’s mail server). You could leave it at localhost if you’re using your own local SMTP server. If you aren’t using your own local SMTP server, you will need to enter a mail server that you have access to (such as your ISP’s mail server). For example, SMTP = mail.earthlink.net .

You should also set a default «From» email address by changing the line that reads ;sendmail_from = [email protected] . For example, sendmail_from = [email protected] .

Don’t Know Your php.ini Location or sendmail_path Path?

If you don’t know where your php.ini is, or what your sendmail_path setting should be, read on.

Your php.ini may be located here: /private/etc/php.ini . And there’s a chance that your sendmail path will be at /usr/sbin/sendmail ). Having said this, each PHP installation is different, so you should check using phpinfo() .

Fortunately, this is easy to do.

phpinfo() is used to view your PHP configuration details. You can do this by creating a .php file with the following line on it: . When you run this in your browser, you will see a full list of PHP configuration variables. Simply search for the lines that contain php.ini and sendmail_path to see the values you need to use.

Источник

Send Email from Localhost using PHP with SMTP and PHPMailer

Localhost is the web developer’s favorite home. Local development environment is always convenient to develop and debug scripts.

Mailing via a script with in-built PHP function. This may not work almost always in a localhost. You need to have a sendmail program and appropriate configurations.

If the PHP mail() is not working on your localhost, there is an alternate solution to sending email. You can use a SMTP server and send email from localhost and it is the popular choice for sending emails for PHP programmers.

This example shows code to use PHPMailer to send email using SMTP from localhost.

mail sending from localhost using smtp

PHP Mail sending script with SMTP

This program uses the PHPMailer library to connect SMTP to send emails. You can test this in your localhost server. You need access to a SMTP server.

Before running this code, configure the SMTP settings to set the following details.

  1. Authentication directive and security protocol.
  2. Configure SMTP credentials to authenticate and authorize mail sending script.
  3. Add From, To and Reply-To addresses using the PHPMailer object.
  4. Build email body and add subject before sending the email.

The above steps are mandatory with the PHPMailer mail sending code. Added to that, this mailing library supports many features. Some of them are,

  • Single and multiple file attachments to the email.
  • Allows rich content in the email body.
  • Provides property to set the alternate mail body to be compatible with older clients.

Set the SMTP Debug = 4 in development mode to print the status details of the mail-sending script.

SMTPDebug = 0; $mail->isSMTP(); $mail->Host = 'SET-SMTP-HOST'; $mail->SMTPAuth = true; $mail->SMTPSecure = "ssl"; $mail->Port = 465; $mail->mailer = "smtp"; $mail->Username = 'SET-SMTP-USERNAME'; $mail->Password = 'SET-SMTP-PASSWORD'; // Sender and recipient address $mail->SetFrom('SET-SENDER-EMAIL', 'SET-SENDER_NAME'); $mail->addAddress('ADD-RECIPIENT-EMAIL', 'ADD-RECIPIENT-NAME'); $mail->addReplyTo('ADD-REPLY-TO-EMAIL', 'ADD-REPLY-TO-NAME'); // Setting the subject and body $mail->IsHTML(true); $mail->Subject = "Send email from localhost using PHP"; $mail->Body = 'Hello World!'; if ($mail->send()) < echo "Email is sent successfully."; >else < echo "Error in sending an email. Mailer Error: ErrorInfo>"; > ?> 

Google and Microsoft disabled insecure authentication

Earlier, programmers conveniently used GMail’s SMTP server for sending emails via PHP. Now, less secure APPs configuration in Google is disabled. Google and Microsoft force authentication via OAuth 2 to send email.

There is ill-informed text going around in this topic. People say that we cannot send email via Google SMTP any more. That is not the case. They have changed the authentication method.

IMPORTANT: I have written an article to help you send email using xOAuth2 via PHP. You can use this and continue to send email using Google or other email service providers who force to use OAuth.

Alternate: Enabling PHP’s built-in mail()

  1. If you do not have access to an email SMTP server.
  2. If you are not able to use xOAuth2 and Google / Microsoft’s mailing service.

In the above situations, you may try to setup your own server in localhost. Yes! that is possible and it will work.

PHP has a built-in mail function to send emails without using any third-party libraries.

The mail() function is capable of simple mail sending requirements in PHP.

In localhost, it will not work without setting the php.ini configuration. Find the following section in your php.ini file and set the sendmail path and related configuration.

Источник

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