Что нового

не отправляет письма(ошибка smtp)

Arei

Скриптер
Сообщения
938
Репутация
115
Здравствуйте, подскажите почему выскакивает ошибка
"Не могу открыть SMTP сокет. Проверьте подключение к Интернету; либо неверные аргументы"
код
Код:
#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#include <GUIConstants.au3>
#include <File.au3>

#Region ### START Koda GUI section ### Form=D:\Documents and Settings\Admin.MICROSOF-290ABD\Рабочий стол\Прогрраммы мои\автоит\Спам машина\Form1.kxf
$Form1 = GUICreate("", 424, 345, 566, 199)

$Label1 = GUICtrlCreateLabel("Имя отправителя", 40, 64, 93, 17)
$Label2 = GUICtrlCreateLabel("Тема письма", 40, 112, 72, 17)
$Label3 = GUICtrlCreateLabel("Тело письма", 40, 152, 70, 17)
$Input1 = GUICtrlCreateInput("1", 160, 64, 121, 21)
$Input2 = GUICtrlCreateInput("2", 160, 112, 121, 21)
$Edit = GUICtrlCreateEdit("", 152, 152, 185, 89)
$Input3 = GUICtrlCreateInput("", 64, 16, 121, 21)
$Input4 = GUICtrlCreateInput("", 264, 16, 121, 21)
$Button1 = GUICtrlCreateButton("Запустить", 192, 288, 75, 25, $WS_GROUP)
$Label4 = GUICtrlCreateLabel("Логин", 24, 24, 35, 17)
$Label5 = GUICtrlCreateLabel("Пароль", 208, 24, 42, 17)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###




$file = FileOpen("1.txt", 0)
$chars = FileRead($file)

$days = StringSplit($chars, @cr)

$days[0] = $days[0]-1





While 1
	$nMsg = GUIGetMsg()
	Switch $nMsg
		Case $GUI_EVENT_CLOSE
			Exit
		Case	$Button1


	$w1 = GUICtrlRead($Input1)
    $w2  = GUICtrlRead($Input2)
	$w3 = GUICtrlRead($Input3)
    $w4  = GUICtrlRead($Input4)
	$w5 = GUICtrlRead($Edit)
	ConsoleWrite($w5)

$SmtpServer = 'smtp.yandex.ru'           ; адрес SMTP сервера
$FromName = $w1              ; имя отправителя
$FromAddress = $w3 & '@yandex.ru'  ; адрес отправителя

$Subject = $w2          ; тема письма
$Body = $w5          ; тело письма (сам текст письма)
$AttachFiles = ''; прикреплённые файлы к письму
$Username = $w3           ; имя пользователя аккаунта, с которого отправляется
$Password = $w4                    ; пароль аккаунта, с которого отправляется



for $i = 1 to $days[0]

$ToAddress = $days[$i]      ; адрес назначения

$BlatArgs = "-t "&$ToAddress&" -f "&$FromAddress&" -s "&$Subject&" -body "&$Body&" -server "&$SmtpServer&" -u "&$Username&" -pw "&$Password&" -attach "&$AttachFiles


    $BlatDLL = DllOpen ("blat.dll")
    Do
        $result=DllCall($BlatDLL,"int","Send","str",$BlatArgs)

        Select
            Case $result[0] = 13
                MsgBox(16,"Ошибка. Код ошибки " & $result[0], "Не могу открыть временный файл во временной папке")

            Case $result[0] = 12
                MsgBox(16, "Ошибка. Код ошибки " & $result[0], "Не указаны или не найдены в реестре аргументы -server или -f")

            Case $result[0] = 3
                MsgBox(16, "Ошибка. Код ошибки " & $result[0], "Не могу прочитать файл с текстом письма или приложенный файл")

            Case $result[0] = 2
                MsgBox(16, "Ошибка. Код ошибки " & $result[0], "Почтовому серверу не понравился адрес отправителя; или он отказал нам в подключении; или неверный пароль; или не найден файл с текстом письма")
            Case $result[0] = 1
                MsgBox(16, "Ошибка. Код ошибки " & $result[0], "Не могу открыть SMTP сокет. Проверьте подключение к Интернету; либо неверные аргументы")
            Case $result[0] <> 0
                MsgBox(16, "Ошибка. Код ошибки " & $result[0], "Неизвестная ошибка")
        EndSelect
    Until $result[0] = 0
    DllClose ($BlatDLL)



	next

	EndSwitch
WEnd


Заранее спасибо.
 

Yuri

AutoIT Гуру
Сообщения
737
Репутация
282
Посмотрел.
DllOpen ("blat.dll")
Этого (blat.dll) у меня нет.
Результат - вывод в консоль SciTE значения "Тело письма" и все.
Писал то же самое без blat.dll, все работало (Тема, От кого, Тело, Аттач)
P.S.
Давно было. Может сейчас и не актуально.
Но, все же - вот ссылка. Хотя большая часть (99%) - не мое.
http://autoit-script.ru/index.php/topic,1539.0.html
 
Автор
A

Arei

Скриптер
Сообщения
938
Репутация
115
blat есть в файловом хранилище.
 

Zaramot

I ♥ AutoIt
Сообщения
1,160
Репутация
660
Можно обойтись и без Blat.dll
Вот пример (подстрой его под себя):
Код:
$FromAddress = '' ;Адрес отправителя. Пример [email protected]
$ToAddress = '' ;Адрес получателя. Пример [email protected]
$Subject = '' ;Тема письма
$Body = '' ;Текст письма
$Attachment = '' ;файл для отправки
$SMTPServer = '' ;SMTP сервер
$Username = '' ;Логин от вашей почты. Пример: [email protected]
$Password = '' ;Пароль дт вашей почты
$Port = '' ;Порт

_SendMail($FromAddress, $ToAddress, $Subject, $Body, $Attachment, $SMTPServer, $Username, $Password, $Port)

Func _SendMail($mFromAddress, $mToAddress, $mSubject, $mBody, $mAttachment, $mSMTPServer, $mUsername, $mPassword, $mPort)
	$str = "http://schemas.microsoft.com/cdo/configuration/"
	$hMAIL = ObjCreate ("CDO.Message")
	With $hMAIL
		.From = $mFromAddress
		.To = $mToAddress
		.Subject = $mSubject
		.TextBody = $mBody
		.AddAttachment ($mAttachment)
	EndWith
	With $hMAIL.Configuration.Fields
		.Item ($str & "sendusing") = 2
		.Item ($str & "smtpserver") = $mSMTPServer
		.Item ($str & "smtpauthenticate") = 1
		.Item ($str & "sendusername") = $mUsername
		.Item ($str & "sendpassword") = $mPassword
		.Item ($str & "smtpserverport") = $mPort
		.Update
	EndWith
	$hMAIL.Send
EndFunc


Проверял на Mail.ru - Работает :smile:

PS Mail Sender - может кому понадобится ;)
 
Автор
A

Arei

Скриптер
Сообщения
938
Репутация
115
мне этот код выдаёт ошибку $hMAIL.Send^error
 

joiner

Модератор
Локальный модератор
Сообщения
3,556
Репутация
628
на форуме выкладывался скрипт программки Send Mail. я его обезобразил как мог :smile:
под свои нужды. сама функция отправки осталась неизменной. и функция шифровки данных при записи их в текстовый документ. ну вобщем не буду все перечислять. моего там мало. факт в другом, ни одного сбоя не было. работает четко.

Код:
#NoTrayIcon
#RequireAdmin
#include <File.au3>
#include <GUIConstants.au3>
#include <WindowsConstants.au3>
#include <EditConstants.au3>
#include <String.au3>
#include <GuiButton.au3>
Global $settings_add, $s_SmtpServer, $s_FromName, $s_FromAddress, $s_ToAddress, $s_Subject, $s_Body, $s_AttachFiles, $s_CcAddress, $s_BccAddress, $s_Username, $s_Password, $IPPort, $ssl
$Form = GUICreate("Mail", 400, 290, -1, -1, BitOR($WS_POPUP, $WS_BORDER))
$Close = GUICtrlCreateLabel("X", 400 - 15, 0, 11, 20)
GUICtrlSetFont(-1, 10, 800, 0, "Comic Sans MS")
GUICtrlSetColor(-1, 0xFFFFFF)
GUICtrlSetBkColor(-1, $GUI_BKCOLOR_TRANSPARENT)
GUICtrlSetCursor(-1, 0)
GUICtrlSetFont(-1, 10, 800, 0, "Comic Sans MS")
GUICtrlSetColor(-1, 0xFFFFFF)
GUICtrlSetBkColor(-1, $GUI_BKCOLOR_TRANSPARENT)
GUICtrlSetCursor(-1, 0)
$Formtitle = GUICtrlCreateLabel("Mail", 0, 4, @DesktopWidth, 20, -1, $GUI_WS_EX_PARENTDRAG)
GUICtrlSetColor(-1, 0xFFFFFF)
GUICtrlSetBkColor(-1, $GUI_BKCOLOR_TRANSPARENT)
$Formtitlebackground = GUICtrlCreateGraphic(0, 0, @DesktopWidth, 22)
GUICtrlSetBkColor(-1, 0x000000)
$Input1 = GUICtrlCreateInput("", 70, 28, 257, 21)
$Input2 = GUICtrlCreateInput("", 70, 52, 257, 21)
$Input3 = GUICtrlCreateInput("", 70, 76, 257, 21)
$Input4 = GUICtrlCreateInput("", 70, 100, 257, 21)
$Input5 = GUICtrlCreateInput("", 70, 124, 257, 21)
$Input6 = GUICtrlCreateInput("", 70, 148, 257, 21)
$Input7 = GUICtrlCreateInput("", 70, 172, 257, 21)
$Input8 = GUICtrlCreateInput("25", 70, 196, 50, 21)
$Label1 = GUICtrlCreateLabel("Тема:", 8, 30, 29, 17)
$Label2 = GUICtrlCreateLabel("Кому:", 8, 54, 46, 17)
$Label3 = GUICtrlCreateLabel("От кого:", 8, 77, 60, 17)
$Label4 = GUICtrlCreateLabel("SMTP:", 8, 105, 32, 17)
$Label5 = GUICtrlCreateLabel("Логин:", 8, 128, 37, 17)
$Label6 = GUICtrlCreateLabel("Пароль:", 8, 152, 40, 17)
$Label7 = GUICtrlCreateLabel("Файл:", 8, 176, 40, 17)
$Label8 = GUICtrlCreateLabel("Порт:", 8, 200, 29, 17)
$Button1 = GUICtrlCreateButton("Отправка", 8, 220, 150, 25, 0)
GUICtrlSetState($Button1, $GUI_DISABLE)
$Button2 = GUICtrlCreateButton("Сохранить", 167, 220, 147, 25, 0)
$Button3 = GUICtrlCreateButton("Загрузить", 167, 250, 147, 25, 0)
$Button4 = GUICtrlCreateButton("Установить", 8, 250, 147, 25, 0)
$fileadd = GUICtrlCreateButton("...", 330, 172, 40, 21)
GUISetState(@SW_SHOW, $Form)

While 1
	$msg = GUIGetMsg()
	Switch $msg
		Case $Close
			Exit
		Case $Button1
			Apply()
			$s_Body = ""
			$s_FromName = ""
			If FileExists($s_AttachFiles) = @error Then GUICtrlSetData($Input7, "")
			If $s_ToAddress = "" Or $s_Subject = "" Or $s_FromAddress = "" Or $s_SmtpServer = "" Or $s_Username = "" Or $s_Password = "" Or $IPPort = "" Then
				MsgBox(0, "", "Не все поля заполнены")
			Else
				GUICtrlSetState($Button1, $GUI_DISABLE)
				GUICtrlSetData($Button1, "Отправляю...")
				InetRead("http://www.yandex.ru")
				If @error Then
					MsgBox(0, "", "Нет соединения")
					GUICtrlSetState($Button1, $GUI_ENABLE)
					GUICtrlSetData($Button1, "Отправка")
				Else
					GUICtrlSetState($Button1, $GUI_DISABLE)
					GUICtrlSetData($Button1, "Отправляю...")
					_INetSmtpMailCom($s_SmtpServer, $s_FromName, $s_FromAddress, $s_ToAddress, $s_Subject, $s_Body, $s_AttachFiles, $s_CcAddress, $s_BccAddress, $s_Username, $s_Password, $IPPort, $ssl = 0)
					GUICtrlSetState($Button1, $GUI_ENABLE)
					GUICtrlSetData($Button1, "Отправка")
				EndIf
			EndIf
			ControlFocus($Form, "", $Button1)
		Case $Button2
			GUICtrlSetState($Button2, $GUI_DISABLE)
			Apply()
			If FileExists($s_AttachFiles) = @error Then GUICtrlSetData($Input7, "")
			If $s_ToAddress = "" Or $s_Subject = "" Or $s_FromAddress = "" Or $s_SmtpServer = "" Or $s_Username = "" Or $s_Password = "" Or $IPPort = "" Then
				MsgBox(0, "", "Не все поля заполнены")
			Else
				Save()
			EndIf
			GUICtrlSetState($Button1, $GUI_ENABLE)
			GUICtrlSetState($Button2, $GUI_ENABLE)
			ControlFocus($Form, "", $Button2)
		Case $Button3
			GUICtrlSetState($Button3, $GUI_DISABLE)
			Load()
			GUICtrlSetState($Button3, $GUI_ENABLE)
			GUICtrlSetState($Button1, $GUI_ENABLE)
			ControlFocus($Form, "", $Button3)
		Case $Button4
			GUICtrlSetState($Button4, $GUI_DISABLE)
			_install()
			GUICtrlSetState($Button4, $GUI_ENABLE)
		Case $fileadd
			$sFile = FileOpenDialog('Выбор файла', '', 'Все файлы (*.*)', "", "", $Form)
			GUICtrlSetData($Input7, $sFile)
			ControlFocus($Form, "", $fileadd)
	EndSwitch
WEnd

Func _INetSmtpMailCom($s_SmtpServer, $s_FromName, $s_FromAddress, $s_ToAddress, $s_Subject = "", $s_Body = "", $s_AttachFiles = "", $s_CcAddress = "", $s_BccAddress = "", $s_Username = "", $s_Password = "", $IPPort = 25, $ssl = 0)
	$objEmail = ObjCreate("CDO.Message")
	$objEmail.From = '"' & $s_FromName & '" <' & $s_FromAddress & '>'
	$objEmail.To = $s_ToAddress
	Local $i_Error = 0
	Local $i_Error_desciption = ""
	If $s_CcAddress <> "" Then $objEmail.Cc = $s_CcAddress
	If $s_BccAddress <> "" Then $objEmail.Bcc = $s_BccAddress
	$objEmail.Subject = $s_Subject
	If StringInStr($s_Body, "<") And StringInStr($s_Body, ">") Then
		$objEmail.HTMLBody = $s_Body
	Else
		$objEmail.Textbody = $s_Body & @CRLF
	EndIf
	If $s_AttachFiles <> "" Then
		Local $S_Files2Attach = StringSplit($s_AttachFiles, ";")
		For $x = 1 To $S_Files2Attach[0]
			$S_Files2Attach[$x] = _PathFull($S_Files2Attach[$x])
			If FileExists($S_Files2Attach[$x]) Then
				$objEmail.AddAttachment($S_Files2Attach[$x])
			Else
				$i_Error_desciption = $i_Error_desciption & @LF & 'File not found to attach: ' & $S_Files2Attach[$x]
				SetError(1)
				Return 0
			EndIf
		Next
	EndIf
	$objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
	$objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = $s_SmtpServer
	$objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = $IPPort
	If $s_Username <> "" Then
		$objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
		$objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = $s_Username
		$objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = $s_Password
	EndIf
	If $ssl Then
		$objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
	EndIf
	$objEmail.Configuration.Fields.Update
	$objEmail.Send
	If @error Then
		SetError(2)
		Return 
	EndIf
EndFunc   ;==>_INetSmtpMailCom

Func Apply()
	$s_SmtpServer = GUICtrlRead($Input4)
	$s_FromAddress = GUICtrlRead($Input3)
	$s_Username = GUICtrlRead($Input5)
	$s_Password = GUICtrlRead($Input6)
	$IPPort = GUICtrlRead($Input8)
	$s_ToAddress = GUICtrlRead($Input2)
	$s_Subject = GUICtrlRead($Input1)
	$s_AttachFiles = GUICtrlRead($Input7)
EndFunc   ;==>Apply

Func Save()
	Apply()
	$Save = _StringEncrypt(1, $s_SmtpServer & "&#38;#8224;" & $s_FromName & "&#38;#8224;" & $s_FromAddress & "&#38;#8224;" & $s_Username & "&#38;#8224;" & $s_Password & "&#38;#8224;" & $IPPort & "&#38;#8224;" & $s_ToAddress & "&#38;#8224;" & $s_Subject & "&#38;#8224;" & $s_AttachFiles & "&#38;#8224;" & $ssl, "Secret")
	$save_sattings = FileSaveDialog("Сохранение настроек", "", "(settings.txt)", "", "settings.txt", $Form)
	If FileExists($save_sattings) Then FileDelete($save_sattings)
	FileWrite($save_sattings, $Save)
EndFunc   ;==>Save

Func Load()
	$settings_add = FileOpenDialog('Выбор файла - Settings.txt', "", '(settings.txt)', '', '', $Form)
	If $settings_add = True Then
		$Load = FileRead($settings_add)
		$Decrypt = _StringEncrypt(0, $Load, "Secret")
		$Settings = StringSplit($Decrypt, "&#38;#8224;", 1)
		GUICtrlSetData($Input4, $Settings[1])
		GUICtrlSetData($Input3, $Settings[3])
		GUICtrlSetData($Input5, $Settings[4])
		GUICtrlSetData($Input6, $Settings[5])
		GUICtrlSetData($Input8, $Settings[6])
		GUICtrlSetData($Input2, $Settings[7])
		GUICtrlSetData($Input1, $Settings[8])
		GUICtrlSetData($Input7, $Settings[9])
	Else
		Return
	EndIf
EndFunc   ;==>Load
 
Верх