Sending mail from windows

7 Command Line Utilities to Easily Send Email Using SMTP

Not only is email very useful for communication between friends and families and sending messages with attachments such as reports, photos, documents, presentations, video clips and music files, it’s also useful for notification purposes. For example, a website monitoring service such as Pingdom has alerts where you’ll be notified through different methods such as email, SMS, twitter or in-app when your server is down. Third party backup software also normally has at least an email notification feature where you can set it up to automatically email you when the backup process has completed or failed.

If you are writing a batch file and want to send an automated email when the batch has completed running or if you’re faced with a third party software that does not even support email notification, then the simple solution is to use a command line email sending tool for Windows. Here we have 7 ways to look at.

  • sender@gmail.com = Replace it with your full Gmail address
  • recipient@email.com = Replace it with the email address that will receive the message
  • YourGmailPassword = Replace it with your Gmail password
  • subject = The subject of the email. Make sure it is enclosed with double quotes if there are spaces. For example, This is a long subject
  • body = The message of the email. Should also enclose with double quotes if there are spaces

1. SwithMail

Out of all the command line email sending tools, we’d consider SwithMail as one of the best in its class, if not the best. Instead of the need to write really long command line options to silently send an email where you might make mistakes and need a few tries to get it right, configuring SwithMail is quite foolproof thanks to the easy to use settings configuration GUI. You even test the email settings to make sure that it is able to successfully send an email.

Other than the standard options such as attachments, CC, BCC that you’d normally find when sending an email, SwithMail supports returning error codes, global variables and wildcard attachments which is very useful to automatically send log files with dated filenames. Below is a working example of SwithMail command line options to send an email using Gmail account.

SwithMail.exe /s /from sender@gmail.com /pass YourGmailPassword /server smtp.gmail.com /p 587 /SSL /to recipient@email.com /sub subject /b message

2. CMail

If you need to use a command line email sending tool that supports proxy, CMail would be your choice as it’s the only one that can support socks and HTTPS based proxy. Other interesting features that can be found in CMail are sending the whole directory content based on wildcard attachment and delivery status notification.

The full working command line to send an email using Gmail is as follows:

CMail.exe -secureport -host:sender@gmail.com:YourGmailPassword@smtp.gmail.com:465 -from:sender@gmail.com -to:recipient@email.com -subject:subject -body:message

3. SendSMTP

Running SendSMTP will bring up an interactive graphical user interface to send emails but at the same time it also supports command line instructions to silently send email with just one line of commands. Although an advanced user would have no problems with the command line arguments, a GUI will greatly help a basic computer user in creating a working config file.

Читайте также:  Выполнение команды от имени другого пользователя linux

Some notable features found in SendSMTP are the ability to save the password as encrypted using 128-bit Rijndael (AES) rather than saving the password as clear text, enable log file to save the activity of the SendSMTP program, and can return codes to report if the send email is successful (0), failed (1), or cannot find settings (2). The full command line for SendSMTP to send email using Gmail is as follow.

SendSMTP.exe /nos /host smtp.gmail.com /port 587 /auth 2 /userid sender@gmail.com /pass YourGmailPassword /from sender@gmail.com /to recipient@email.com /subject subject /body message

However, if you’ve saved the settings as default from the GUI which will create a SendSMTP.ini file at the same location as the program, a much shorter command line can be used to send an email.

Do note that there are 2 versions available on the download page. You will need the newer version with the bigger file size to support sending email using Gmail because the old version does not support SASL authentication.

4. mailsend

Comparing with the utilities mentioned above, mailsend is a simpler command line tool to send email using SMTP. It doesn’t have fancy features such as loading config from an external file, password encryption, GUI, error codes and etc. However, an interesting feature found in mailsend that is not available on other command line email sending tool is the ability to show SMTP server information by using the -info option.

mailsend is available for both Windows and Linux operating system. Below is the example command line for mailsend to send an email using Gmail.

mailsend1.17b15.exe -t recipient@email.com -f sender@gmail.com -ssl -port 465 -auth -smtp smtp.gmail.com -sub subject -M message -user sender@gmail.com -pass YourGmailPassword

5. Send-It-Quiet

Send-It-Quiet is the smallest command line SMTP mailer utility that weighs only 14KB in size and this is made possible with .NET Framework. This would also mean that you need to have .NET Framework 3.5 installed to run Send-It-Quiet. Send-It-Quiet only comes with very basic parameters that are enough to send an email. Possibly the only extra features found in Send-It-Quiet are the return value of ERRORLEVEL and also the flexibility of manually adding the parameters to registry.

The command line to send an email using Send-It-Quite with a Gmail account is:

senditquiet.exe -s smtp.gmail.com -port 587 -u sender@gmail.com -protocol ssl -p YourGmailPassword -f sender@gmail.com -t recipient@email.com -subject subject -body message

6. SendEmail

SendEmail is written in Perl but there is no need to install Perl in Windows for this command line mailer utility to work. SendEmail was last updated in 2009, but the last version has TLS support which means it can send email using Gmail SMTP. In terms of features, it is quite similar to Send-It-Quiet which only supports the standard email sending options such as to, from, subject, body, attachment, etc. SendEmail is available for both Windows and Linux operating systems.

Here is an example of the command line options that can send email using Gmail SMTP.

sendEmail.exe -o tls=yes -f sender@gmail.com -t recipient@email.com -s smtp.gmail.com:587 -xu sender@gmail.com -xp YourGmailPassword -u subject -m message

7. PowerShell

PowerShell is included in Windows operating systems since Windows 7 which means you can actually use a powershell script to send an email through Gmail SMTP without any of the command line tools mentioned above.

The sample script that can be downloaded at the link below is a very basic one that is meant to only send an email without attachment support. Simply download the ps1 script, open it with Notepad or Windows PowerShell ISE and change the credentials located at line number 8. The command line to run the powershell script is as follows. Make sure you update the path to the .ps1 file.

Powershell.exe -executionpolicy remotesigned -File C:\Users\Raymond\sendemail.ps1

The popular Blat is not included in the list because it does not support SSL which means it cannot send email using Gmail SMTP. Bmail (last updated in 2004), cmdsendmail which is a part of CommandLine Tools, and XmlSendmail are also example of command line send mail utility that doesn’t support SSL.

Читайте также:  Портативный браузер для линукс

Отправка почты через sendmail в ОС Windows

Наверняка многие использовали и используют функцию mail() для отправки сообщение e-mail. Но в ОС Windows невозможно отправить почту используя только скрипты php и эту ф-цию. Нужны программные средства:

1 Установить полноценный почтовый сервер, например Kerio Connect (не реклама)
2 Использовать скрипты (классы) для работы с почтой: Zend_mail, PHPmailer и т.д.
3 Установить готовые веб-серверы типа Денвер, XAMPP
4 Воспользоваться эмуляцией демона sendmail для OS Windows

Пока не поздно подумаем о лете и ЖАРЕ, присмотримся к кондиционерам, vrf системы — наше спасение.

Лично я не любитель использовать собранные проекты, такие как Денвер, XAMPP и им подобным. Люблю использовать то, что будет жить на сервере, т.е. по-отдельности устанавливаю сервисы. Устанавливать какой-то мыльный сервере, тоже не охота — его нужно ломать (большинство платные), настраивать и тд. Что же делать?

На помощь пришел 4-й пункт! Качаем, распаковываем, и начинаем настройку.

Настройка sendmail.ini

И так в созданном каталоге будет файл sendmail.ini, его и надо править — это главный файл конфигурации:

где
smtp_server — сервер отправки почты;
smtp_port — порт сервера;
smtp_ssl — использование сертификата, если не знаете пусть будет auto;
default_domain — основной домен для сервера отправки сообщения;
error_logfile — лог-файл ошибок, название любое, даже можно написать путь, где будет храниться файл;
debug_logfile — лог-файл отладочной информации (деббагер) в нем видно все «разговоры» с сервером;
auth_username и auth_password — данные авторизации на сервере;
force_sender — от кого будет послано сообщение;
force_recipient — кому будет послано, но оставляем пустым, т.к. эту инфу указываем в скрипте;
hostname — ставим такое же, как и default_domain.

Хочу напомнить, что не все серверы, из-за спама, разрешают их юзать, например при написании статьи я попытался подключиться к smtp.yandex.ru:25 ничего не вышло, кол-во писем в ящике показывает, но не отправляет.
Иная ситуация с smtp.mail.ru:2525, причем порт не по-умолчанию, стандартные тоже не работал, но в помощи, на сайте, написано, что есть два других порта, я воспользовался и получилось.

Настройка php.ini

Находим секцию [mail function]

комментируем все строки, кроме пути к sendmail, в этом пути прописываем полный путь к бинарнику.

Пишем простейший скрипт

ну пояснять тут ничего не буду, самый первый линк этой статьи видет на пояснения.

Разбор логов

Это вид простейшего лога. Ессно все параметры типа легальное мыло, домены, ай-пи адреса я заменил на вымышленные, что бы потом меня не спамили.

Ну и в ответ, на своем почтовом ящике, куда я послал почту я её и получил.

Сам сервис для отправка почты через sendmail в ОС Windows можете взять тут

Удачи, пиши отзывы, кликайте на рекламу )))

Статья просмотренна 88106 раз, зашло посетителей 31208

326 23 комментария http%3A%2F%2Fblog.nagaychenko.com%2F2010%2F02%2F23%2F%25d0%25be%25d1%2582%25d0%25bf%25d1%2580%25d0%25b0%25d0%25b2%25d0%25ba%25d0%25b0-%25d0%25bf%25d0%25be%25d1%2587%25d1%2582%25d1%258b-%25d1%2587%25d0%25b5%25d1%2580%25d0%25b5%25d0%25b7-sendmail-%25d0%25b2-%25d0%25be%25d1%2581-windows%2F %D0%9E%D1%82%D0%BF%D1%80%D0%B0%D0%B2%D0%BA%D0%B0+%D0%BF%D0%BE%D1%87%D1%82%D1%8B+%D1%87%D0%B5%D1%80%D0%B5%D0%B7+sendmail+%D0%B2+%D0%9E%D0%A1+Windows 2010-02-23+17%3A43%3A31 maxnag http%3A%2F%2Fblog.nagaychenko.com%2F%3Fp%3D326 в “Отправка почты через sendmail в ОС Windows”

извини, но статья не раскрыта!можно было и поподробнее написать!

Читайте также:  Vmware при установке mac os

А что там описывать, есть бинарник, к нему конфиг, показал как настроить. Работает. Что не так. Положить в рот и разжевать?

тогда из таких, кому разжовывать, говно-девелоперы получаются.

заебали со своими девелоперами! Есть правило в русском языке, которое запрещает использование иностранных слов, когда есть русский аналог. РАЗРАБОТЧИК, а не девелопер.

Да, такое слово есть, не спорю.
Целый день, мы — разработчики работаем со специфической литературой которая написана на английском языке (90%), также разговариваем с клиентами и для нас эти слова, девелопер, инстанс, полиси, нода и прочее стали «родные» и понятные, а зачем их переводить на свой язык, если мы, в своём круге, понимаем друг друга? И данный блог, простите дневник, предназначен для этого круга людей.
Иногда я сам думаю, чего я пишу ишью, если могу написать задание (проблема), но такова специфика работы. В блоге посвященному русскому языку такого не должно быть, а здесь будет.

ЗЫ в последнее время на работе я всё пишу на английском и граница между двумя языками исчезает для меня.

Помогите мне объяснить как можно настроить sendmail на одном сервере ,чтоб можно было несколько отправителей , типо 4 сайта на сервере , но в php.ini и в sendmail только можно одного отправителя вписать со всеми настройками ,или нужно под каждого отправителя отдельный движек sendmail ?

Советую Вам более подробно изучить что такое http://ru.wikipedia.org/wiki/Sendmail и вам всё станет ясно. Он умеет делать всё.

Приветствую. судя по статье так она про Sendmail в нэти везде одинаковая чтобы снять заглушку надо приминить
username=
password=
вот или я бестолковый или лыжи едут, username= и password= чего надо в водить smtp адреса от которого будит идти рассылка или отправка писем если да то опять не то, вот подскажите кто знает вот к примеру у меня внешний айпишник то есть ip статический возьмём к примеру локал хост денвер ну что хамп что денвер у них в sendmail заглушка стоит, вот установил я к примеру денвер ip провайдера внешний тоесть сервак в нэти через ip доступин виден, вот установил я к примеру денвер, вот каким макаровым мне снять заглушку в sendmail не таким способом как выше а без username= и password= то и есть по другому говоря есть скрипт(ы) php формата анонимной отправки писем, с хостингов они работают но банятся, вот как мне настроить или какой установить sendmail чтоб php скрипт анонимнай отправки писем отправлялся с компа с локального сервака sendmail может тут кто подскажет.

Программа sendmail которую мы скачивали в 4-ом пункте она бесплатная или ломаная?

Бесплатная, можете юзать, для тестов самое оно.

Спасибо за статью, все очень понятно. Получилось с первого раза настроить. Весь инет до этого облазил нигде толкового описания нет. Кстати прога какие нибудь ограничения имеет?

Пожалуйста. На продакшене у вас врятли будет Windows, а это прога просто эмулирует работы подобной проги в *nix системах.
Она для тех кто по каким-то причинам не хочет переходить на Linux, являясь программистом PHP, а остаётся на Windows.

как присоединить файл архив к письму?

Привет, всё очень просто — вот тут описано

А без smtp сервера mail.ru? чтобы оно само? как на линукс — нажал mail() и оно ушло (на линукс разумеется установлен postfix), вот и ищу ему альтернативу под винду, так чтоб сам отправлял в инет, а не через сторонние сервисы

Спасибо большое. 3 дня подряд не смог сделать

Подскажите как настроить почтовый сервер на домашнем ПК, у меня имеется домен, домен-регистратор разрешает вносить все необходимые записи.

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