Send mail from windows

Настройка sendmail под Windows

Данная статья входит в цикл статей, посвященных установке веб сервера на windows.

Установка веб сервера на windows
Настройка и защита apache под windows
Бесплатный ДНС сервер
Настройка php
Настройка mysql
Настройка phpmyadmin
Настройка sendmail (эта статья)
Настройка ftp сервера FileZilla

В этой статье я расскажу как установить и настроить sendmail на домашнем сервере под windows.
Для начала скачайте комплект sendmail.
Если у вас уже стоит sendmail можете его удалить, а на его место скопировать скаченные файлы.
Особенно это касается тех, кто устанавливал сервер с помощью xampp.
Дело в том, что в последних версиях xampp лежит новая версия sendmail, лично я так и не смог его запустить, к тому же он работает с уже другим типом конфигурации.
Возможно проблемы с этим новым sendmail и будут решены в дальнейшем, а пока предлагаю использовать старый проверенный вариант, который работает как «трактор».
Так же в архиве лежит две библиотеки, с помощью которых sendmail может работать с защищенными соединениями TLS, типа почты гугла(gmail).

Скачали архив, распаковали, закачали файлы в папку sendmail, если такой папки нет, создайте ее.
Для xampp это путь /xampp/sendmail.
Теперь открывайте настройки sendmail.ini, в архиве находится пример этого файла с русскими комментариями.
Привожу пример файла настроек

; конфигурационный файл sendmail

; здесь укажите сервер исходящей почты
smtp_server=smtp.mail.ru

; порт smtp, если обычный режим отправки, то порт будет 25
; если сервер работает в защищенном режиме (TLS), то порт 465, например почта гугла работает через 465 порт
smtp_port=25

; домен по умолчанию (совсем не обязательно)
;default_domain=local

; лог ошибок
error_logfile=error.log

; лог отправки, необходим на стадии тестирования. содержит весь текст переговоров с сервером при отправке писем.
debug_logfile=debug.log

; Если smtp сервер с авторизацией, укажите логин пароль(без кавычек), если без авторизации ничего не пишите
auth_username=
auth_password=

; если перед отправкой почты сервер требует авторизацию через POP, заполните эти поля
;pop3_server=
;pop3_username=
;pop3_password=

; email адрес, от которого идет отправка, вставится в заголовок «From: »
; если отправка писем идет через mail.ru, здесь обязательно должен быть адрес, через который произведена авторизация.
force_sender=

; хост, который указывается при авторизации в команде ehlo/helo
; указывайте домен, через который авторизуетесь
hostname=mail.ru

Вносите свои данные, логин-пароль и т.д. и все готово.
Сейчас настройте PHP, чтобы он мог использовать sendmail.
Откройте php.ini и найдите следующие строки

[mail function]
; SMTP = localhost
; smtp_port = 25
; sendmail_from = postmaster@localhost
sendmail_path = «\xampp\sendmail\sendmail.exe -t»

Первые строки указанные здесь закройте комментарием как показано (они не нужны), нужна только последняя строка указанная здесь, это путь до sendmail. Укажите свой путь и снимите комментарий (;) если он стоит.
Теперь перегружайте сервер и все готово, функция mail() должна работать.
Если возникают проблемы с отправкой почты, смотрите файлы error.log и debug.log в sendmail(если вы их конечно включили в настройках sendmail.ini)

Другие статьи, посвященные запуску сервера на windows

Установка веб сервера на windows
Настройка и защита apache под windows
Бесплатный ДНС сервер
Настройка php
Настройка mysql
Настройка phpmyadmin
Настройка sendmail (эта статья)
Настройка ftp сервера FileZilla

Комментарии

03.12.2010 Andrei
Если у мя сервер www.server.ru , то в
smtp_server=smtp.server.ru указываю так?

04.12.2010 админ
Andrei, совсем не обязательно.
Смотря как настроен smtp сервер.
Чаще всего mail.server.ru или smtp.server.ru. А может быть и без поддомена, например просто server.ru.
Это надо узнать там, где smtp сервер находится.

05.12.2010 Sheg
Письмо почему то не доходит.
В error.log:
SSL is not available on this server.
В чём проблема, smtp Гугловский.

05.12.2010 админ
Sheg, в ошибке сказано, что ваш сервер не поддерживает SSL соединение. Гугловская почта работает только в защищенном режиме SSL, поэтому вам нужно установить поддержку SSL для sendmail.
http://webi.ru/webi_files/sendmail_ssl.html — здесь комплект с поддержкой SSL.

09.12.2010 Вячеслав.
Все настроил, при отправке письма скрипт ошибок не выдает — но в итоге, письмо для адресата так и не доходит.
В чем может быть проблема ?
Спасибо.

09.12.2010 админ
Вячеслав, включите логи.
Лог ошибок и лог отправки и посмотрите в эти файлы.
И сразу все будет ясно.

10.12.2010 Вячеслав.
Логи включены — ни каких сообщение об ошибках нет.

10.12.2010 Evengar
Вчера всё работало норм, сегодня письмо не доходит через мейл.ру. Ошибка Socket Error # 10054 Connection reset by peer.

11.12.2010 админ
Вячеслав, ну а в debug.log что?
Там ошибок нет, по этим логам письмо отправляется?

11.12.2010 админ
Evengar, ну если вчера отправлялось, а сегодня нет, значит проблемы с вашей связью или с сервером mail.ru

21.12.2010 Алексей
У меня sendmail даже на *.exe никак не реагирует, не говоря о скриптах, и в логах тож ниче нет(((

21.12.2010 админ
Алексей, можно подробнее? Что значит «sendmail на *.exe не реагирует»?

26.12.2010 Виталий
debug — 31457280 250-8BITMIME 250-AUTH PLAIN LOGIN 250 STARTTLS
10.12.26 11:50:44 ** Authenticating as er45633
10.12.26 11:50:44 >> STARTTLS
10.12.26 11:50:44
10.12.26 11:50:44 ** Disconnected.
10.12.26 11:50:44 ** Disconnected.
10.12.26 11:50:44 ** Disconnected.
10.12.26 11:50:44 ** Socket Error # 10054 Connection reset by peer.

и письмо не отправляется в чем причина , что не так.

26.12.2010 админ
Виталий, что-то не совсем понятно. вроде начинается защищенное соединение и обрывается.
с другими серверами пробовали коннектиться?

04.01.2011 Алексей К.
Та же проблема с ошибкой:
«Socket Error # 10054 Connection reset by peer.»

И еще, по моему на Unix такой ошибки нету. Но письма все-равно не отправляются.

04.01.2011 Алексей К.
Спасибо вам большое .
Все получилось при использовании другого сервера почты!

04.01.2011
И еще вопрос,до каких размеров будет расти debug.log ? Или его можно отключить?

04.01.2011 админ
конечно лог отправки и лог ошибок можно отключить, просто удалите эту строку из конфига или закройте комментарием (;)

05.01.2011 Алексей К.
Спасибо еще раз! С Новым годом.

10.01.2011 Alex
Подскажите пожалуйста. Я первый раз пытаюсь настроить sendmail.
Вообщем если я правильно понял настройки которые в sendmail.ini это для почты с которой будет отправляться письма, а адресс почты который указан в mail(); это куда будет производиться отправка. Если да, все делаю по примеру, почта у меня на гугле:
smtp_server=smtp.gmail.com
smtp_port=587
auth_username=name@gmail.com
auth_password=pass
force_sender=name@gmail.com
hostname=gmail.com

log из debug.log:

11.01.10 21:33:22 ** — MESSAGE END —
11.01.10 21:33:22 ** Connecting to smtp.gmail.com:465
11.01.10 21:33:23 ** Disconnected.
11.01.10 21:33:23 ** Disconnected.
11.01.10 21:33:23 ** Disconnected.
11.01.10 21:33:23 ** Error connecting with SSL.

log из error.log:

11.01.10 21:33:23 : Error connecting with SSL.

Send-Mail Message

Sends an email message.

Syntax

Description

The Send-MailMessage cmdlet sends an email message from within PowerShell.

You must specify a Simple Mail Transfer Protocol (SMTP) server or the Send-MailMessage command fails. Use the SmtpServer parameter or set the $PSEmailServer variable to a valid SMTP server. The value assigned to $PSEmailServer is the default SMTP setting for PowerShell. For more information, see about_Preference_Variables.

The Send-MailMessage cmdlet is obsolete. This cmdlet does not guarantee secure connections to SMTP servers. While there is no immediate replacement available in PowerShell, we recommend you do not use Send-MailMessage . For more information, see Platform Compatibility note DE0005.

Examples

Example 1: Send an email from one person to another person

This example sends an email message from one person to another person.

The From, To, and Subject parameters are required by Send-MailMessage . This example uses the default $PSEmailServer variable for the SMTP server, so the SmtpServer parameter is not needed.

The Send-MailMessage cmdlet uses the From parameter to specify the message’s sender. The To parameter specifies the message’s recipient. The Subject parameter uses the text string Test mail as the message because the optional Body parameter is not included.

Example 2: Send an attachment

This example sends an email message with an attachment.

The Send-MailMessage cmdlet uses the From parameter to specify the message’s sender. The To parameter specifies the message’s recipients. The Subject parameter describes the content of the message. The Body parameter is the content of the message.

The Attachments parameter specifies the file in the current directory that is attached to the email message. The Priority parameter sets the message to High priority. The -DeliveryNotificationOption parameter specifies two values, OnSuccess and OnFailure. The sender will receive email notifications to confirm the success or failure of the message delivery. The SmtpServer parameter sets the SMTP server to smtp.fabrikam.com.

Example 3: Send email to a mailing list

This example sends an email message to a mailing list.

The Send-MailMessage cmdlet uses the From parameter to specify the message’s sender. The To parameter specifies the message’s recipients. The Cc parameter sends a copy of the message to the specified recipient. The Bcc parameter sends a blind copy of the message. A blind copy is an email address that is hidden from the other recipients. The Subject parameter is the message because the optional Body parameter is not included.

The Credential parameter specifies a domain administrator’s credentials are used to send the message. The UseSsl parameter specifies that Secure Socket Layer (SSL) creates a secure connection.

Parameters

Specifies the path and file names of files to be attached to the email message. You can use this parameter or pipe the paths and file names to Send-MailMessage .

Type: String [ ]
Aliases: PsPath
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Specifies the email addresses that receive a copy of the mail but are not listed as recipients of the message. Enter names (optional) and the email address, such as Name .

Type: String [ ]
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Specifies the content of the email message.

Type: String
Position: 2
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Specifies that the value of the Body parameter contains HTML.

Type: SwitchParameter
Aliases: BAH
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Specifies the email addresses to which a carbon copy (CC) of the email message is sent. Enter names (optional) and the email address, such as Name .

Type: String [ ]
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as User01 or Domain01\User01. Or, enter a PSCredential object, such as one from the Get-Credential cmdlet.

Credentials are stored in a PSCredential object and the password is stored as a SecureString.

For more information about SecureString data protection, see How secure is SecureString?.

Type: PSCredential
Position: Named
Default value: Current user
Accept pipeline input: True
Accept wildcard characters: False

Specifies the delivery notification options for the email message. You can specify multiple values. None is the default value. The alias for this parameter is DNO.

The delivery notifications are sent to the address in the From parameter.

The acceptable values for this parameter are as follows:

  • None : No notification.
  • OnSuccess : Notify if the delivery is successful.
  • OnFailure : Notify if the delivery is unsuccessful.
  • Delay : Notify if the delivery is delayed.
  • Never : Never notify.

These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the DeliveryNotification parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values.

Type: DeliveryNotificationOptions
Aliases: DNO
Accepted values: None, OnSuccess, OnFailure, Delay, Never
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Specifies the type of encoding for the target file. The default value is utf8NoBOM .

The acceptable values for this parameter are as follows:

  • ascii : Uses the encoding for the ASCII (7-bit) character set.
  • bigendianunicode : Encodes in UTF-16 format using the big-endian byte order.
  • oem : Uses the default encoding for MS-DOS and console programs.
  • unicode : Encodes in UTF-16 format using the little-endian byte order.
  • utf7 : Encodes in UTF-7 format.
  • utf8 : Encodes in UTF-8 format.
  • utf8BOM : Encodes in UTF-8 format with Byte Order Mark (BOM)
  • utf8NoBOM : Encodes in UTF-8 format without Byte Order Mark (BOM)
  • utf32 : Encodes in UTF-32 format.

Beginning with PowerShell 6.2, the Encoding parameter also allows numeric IDs of registered code pages (like -Encoding 1251 ) or string names of registered code pages (like -Encoding «windows-1251» ). For more information, see the .NET documentation for Encoding.CodePage.

Type: Encoding
Aliases: BE
Accepted values: ASCII, BigEndianUnicode, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32
Position: Named
Default value: UTF8NoBOM
Accept pipeline input: True
Accept wildcard characters: False

The From parameter is required. This parameter specifies the sender’s email address. Enter a name (optional) and email address, such as Name .

Type: String
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Specifies an alternate port on the SMTP server. The default value is 25, which is the default SMTP port.

Type: Int32
Position: Named
Default value: 25
Accept pipeline input: True
Accept wildcard characters: False

Specifies the priority of the email message. Normal is the default. The acceptable values for this parameter are Normal, High, and Low.

Type: MailPriority
Accepted values: Normal, High, Low
Position: Named
Default value: Normal
Accept pipeline input: True
Accept wildcard characters: False

Specifies additional email addresses (other than the From address) to use to reply to this message. Enter names (optional) and the email address, such as Name .

This parameter was introduced in PowerShell 6.2.

Type: String [ ]
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Specifies the name of the SMTP server that sends the email message.

The default value is the value of the $PSEmailServer preference variable. If the preference variable is not set and this parameter is not used, the Send-MailMessage command fails.

Type: String
Aliases: ComputerName
Position: 3
Default value: $PSEmailServer
Accept pipeline input: True
Accept wildcard characters: False

The Subject parameter isn’t required. This parameter specifies the subject of the email message.

Type: String
Aliases: sub
Position: 1
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

The To parameter is required. This parameter specifies the recipient’s email address. If there are multiple recipients, separate their addresses with a comma ( , ). Enter names (optional) and the email address, such as Name .

Type: String [ ]
Position: 0
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

The Secure Sockets Layer (SSL) protocol is used to establish a secure connection to the remote computer to send mail. By default, SSL is not used.

Type: SwitchParameter
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Inputs

You can pipe the path and file names of attachments to Send-MailMessage .

Читайте также:  Какими командами устанавливать линукс
Оцените статью