Sign in to follow this  
Followers 0
mikeytown2

SSL Gmail with OpenSSL

64 posts in this topic

#1 ·  Posted (edited)

This sends out an email using a gmail account. It connects to the sever with OpenSSL using TLS or Transport Layer Security. It should work with other email services using SSL.

In order to get this script to run you need to grab openssl

http://www.openssl.org/related/binaries.html

Win32OpenSSL_Light-0_9_8i.exe

All you need to do is fill in some variables to test this (like your gmail username)

Let me know how this works for you.

EDIT

I found out about the new run command in the latest beta, you can grab input and output from the cmd line! In short the v2 no longer uses tempfiles and it only uses the send command once, so i think it much more behaved, check it out! I also rewrote the code so it has a nice looking loop to it.

EDIT

Updated _Base64, 250% speed increase!

EDIT -October 17th, 2008

Due to the changes in versions past v3.2.12.0 this script in its current form doesn't work. I did some quick hacks and got it flying again but its not elegant. I'm calling this version 2.1. Thanks ptrex for showing some interest in this :o

EDIT -October 20th, 2008

Version 3.0 released with these functions

_SMTP_Connect

_SMTP_Login

_SMTP_SendEmail

_SMTP_Disconnect

EDIT -October 20th, 2008

3.1

Added debug to console and fixed some internal issues

Timeout set for 25 seconds (50*500). Which means that if you enter the wrong user/pass/server info you Might have to wait 25 seconds because it is waiting for a reply that is not coming.

ssl.au3

SMTP_ssl_V2.au3

_Base64.au3

SMTP_ssl_V2.1.au3

SMTP_ssl_V3.1.au3

SMTP_ssl_V3.1_Example.au3

Edited by mikeytown2

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Over on the support thread i got this

Hi - Can we use this as the basis for a gmail notifier replacement.... ?

Darren here ya go, i got the info on how to do this from here

http://en.wikipedia.org/wiki/POP3

Make sure your gmail account is set for pop3. So now i have one program that can send mail and another one that can read messages. You still need openssl for POP to work, but not base64. Enjoy! :o

EDIT

I uploaded the new version that uses the new functions in the beta Run, check it out! The loop has been redone as well.

EDIT - October 17, 2008

Hacked code so it works with newest version of AutoIt. See changes in first post for details.

EDIT - October 20, 2008

Version 3.0 released with these functions

_POP_Connect

_POP_Login

_POP_GetStats

_POP_GetList

_POP_GetMessage

_POP_Disconnect

EDIT - December 30, 2008

Version 3.1 addresses the changes made to the gmail pop server.

had to change the way my openssl gui fix works; its a little archaic but it should work.

EDIT - January 7, 2008

Version 3.2 Fixes a timeout issue

POP_ssl.au3

POP_ssl_V2.au3

POP_ssl_V2.1.au3

POP_ssl_V3.0.au3

POP_ssl_V3.0_Example.au3

POP_ssl_V3.1.au3

POP_ssl_V3.1_Example.au3

POP_ssl_V3.2_Example.au3

POP_ssl_V3.2.au3

Edited by mikeytown2

Share this post


Link to post
Share on other sites

Many Thanks.....

Will play with it and see what happens...

Share this post


Link to post
Share on other sites

Many Thanks.....

Will play with it and see what happens...

after the script ends it seems like the ctrl key is held down. I have to restart to fix it. does this happen to you at all

[center]AutoIT + Finger Print Reader/Scanner = COOL STUFF -> Check Out Topic![/center][center][font=Arial Black]Check out ConsultingJoe.com[/font][/center][center]My Scripts~~~~~~~~~~~~~~Web Protocol Managing - Simple WiFi Scanner - AutoTunes - Remote PC Control V2 - Audio SpectrascopePie Chart UDF - At&t's TTS - Custom Progress Bar - Windows Media Player Embed[/center]

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

When it ended did it ask you to kill the child processes? I have this as my endscript function as cleanup.

Func endscript()
    If ProcessExists("openssl.exe") Then
        $s = MsgBox(4, "Kill Child Processes?", "Do you want to kill the command prompt and openssl?")
        If $s = 6 Then
            ProcessClose("cmd.exe")
            ProcessExists("openssl.exe")
            While ProcessExists("openssl.exe")
                ProcessClose("cmd.exe")
                ProcessClose("openssl.exe")
            WEnd
        EndIf
    EndIf
EndFunc ;==>endscript

Zerocool, do you think this is causing it? or could it be my multiple usage of blockinput? I my self don't have the problem of the ctrl key. What about the send program, did that cause you problems as well? They are practically the same, so if one works and the other doesn't i would place the blame on openssl. Try Killing the script midstream and see if the ctrl key is still stuck.

Other then that did it work?

EDIT

I got an idea, in this block add this to kill openssl early

ElseIf StringInStr($aArray[$i], ".") And $State_R = 5 Then;I need better Dection Here
                Sleep(250)
                BlockInput(1)
                WinActivate(@SystemDir & "\cmd.exe")
                WinWaitActive(@SystemDir & "\cmd.exe")
                Send("QUIT{ENTER}")
                BlockInput(0)
                $State_R = 6
                $FileLineStart = $i + 1
                ProcessClose("openssl.exe")
Edited by mikeytown2

Share this post


Link to post
Share on other sites

It did ask to kill processes and I said yes, and thats when it did that but, the very first time it worked and did not do the ctrl thing. but after i tried again it stopped and didn't do any thing, the screen said it could't encode or conver or something, I think the number was 503. It just stopped. I will try what you said.

thanks a lot


[center]AutoIT + Finger Print Reader/Scanner = COOL STUFF -> Check Out Topic![/center][center][font=Arial Black]Check out ConsultingJoe.com[/font][/center][center]My Scripts~~~~~~~~~~~~~~Web Protocol Managing - Simple WiFi Scanner - AutoTunes - Remote PC Control V2 - Audio SpectrascopePie Chart UDF - At&t's TTS - Custom Progress Bar - Windows Media Player Embed[/center]

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

zerocool, are you trying to send (SMTP) or receive(POP3) when you get the errors? I found that a SMTP server will give a Error: 503 "Needs recipient" which means that you forgot to fill in who the email was going to. Then again that was the very line that was giving me all the problems with openssl. when ever you start a line with R in openssl it thinks you want to reconnect, yeah kinda dumb if you ask me. anyway the -ign_eof took care of that problem. But it might not have...

Comment out the hide the command prompt and then run it again and look at the cmd window, let me know if you get any errors once you have connected.

Thanks!

PS. the code i gave you above was for pop not smtp, but you get the idea, cus they are oh so similar.

Edited by mikeytown2

Share this post


Link to post
Share on other sites

Hey I updated some code, I'm using the new beta run functions with the standard_i/o_flag (I didn't know about it). Pretty slick if you ask me :geek: . There was one bug with it so i do have to use a Send() once, but thats a lot better then before, and now the cmd prompt is hidden.

I also made the loop smarter, so you can feed it any command, and its fairly easy to change commands as well.

Go grab V2 of the SMTP and POP program and let me know how they work :o

Share this post


Link to post
Share on other sites

hey guy !

really amazing work !

how did you do to know the command to send to the pop server ?

i want to retrieve my mails with our domino server (SSL v2)

it works to connect, but it blocks with the send command

i don't know what to send to the server for it to work

if you have any ideas ...


-- Arck System _ Soon -- Ideas make everything

"La critique est facile, l'art est difficile"

Projects :

[list] [*]Au3Service : Run your exe as service V3 / Updated 29/07/2013 Get it Here [/list]

Share this post


Link to post
Share on other sites

hey guy !

really amazing work !

how did you do to know the command to send to the pop server ?

From Post #2

If you go to Dialog example in the wiki it shows you how POP works

i want to retrieve my mails with our domino server (SSL v2)

it works to connect, but it blocks with the send command

i don't know what to send to the server for it to work

if you have any ideas ...

Let me make sure i understand here. Your server is using Version 2 of the SSL protocol. How old is domino? Is it apart of Lotus Notes? (I did a google on it)

Well to answer you question, in order to send out an email you need to use a SMTP server. Here is a wiki on the subject: Simple Mail Transfer Protocol. FYI I use ethereal to make sure my scripts are working.

The scripts i made here where kinda like a proof, there not the best but they do get the job done for simple SSL/TLS communication. If someone could use the dll's that come with openssl then this would a lot more portable (no need to install openssl). Just some thoughts. I'm gald to see you found this useful! :o

Share this post


Link to post
Share on other sites

Hi!

Forgive me for my noobish question...but what exactly am I supposed to do once I get the Command Tracer GUI?

My exe seems to stop there itself...when I point my cursor at the tray icon..its says

Line: Sleep(50)

What am I missing here?

By the way, FYI I am behind my Univ's Firewall (could that be the problem?? :o )


I believe we should all pay our tax with a smile. I tried - but they wanted cash!

Share this post


Link to post
Share on other sites

Hi!

Forgive me for my noobish question...but what exactly am I supposed to do once I get the Command Tracer GUI?

My exe seems to stop there itself...when I point my cursor at the tray icon..its says

Line: Sleep(50)

What am I missing here?

By the way, FYI I am behind my Univ's Firewall (could that be the problem?? :o )

Do you have openssl installed in c:\OpenSSL ? this script requires that in order to run. you can grab the installer from my first post

Also what code are you using? i have 4 of them in this thread.

Share this post


Link to post
Share on other sites

Do you have openssl installed in c:\OpenSSL ? this script requires that in order to run. you can grab the installer from my first post

Also what code are you using? i have 4 of them in this thread.

Hi Mikey,

Thanx for help.

Yeah I do have openSSL installed (grabbed the installer from ur post itself :o)

And as far as codes are concerned, I have put _Base64.au3 and ssl.au3 in C:\OpenSSL folder. Then I compiled SMTP_ssl_V2.au3 with Beta compiler (v3.1.1.110) after changing the personal details. Then I double-click the compiled exe to launch the program which asks for username and password. After I fill them in, it shows me a notepad-kind of are titled Command Tracer. Then it remains there forever!

That's the problem.

Thanx for help....and btw nice job! :geek:


I believe we should all pay our tax with a smile. I tried - but they wanted cash!

Share this post


Link to post
Share on other sites

#14 ·  Posted (edited)

And as far as codes are concerned, I have put _Base64.au3 and ssl.au3 in C:\OpenSSL folder. Then I compiled SMTP_ssl_V2.au3 with Beta compiler (v3.1.1.110) after changing the personal details. Then I double-click the compiled exe to launch the program which asks for username and password. After I fill them in, it shows me a notepad-kind of are titled Command Tracer. Then it remains there forever!

That's the problem.

I should apologize for my naming convention, its a little misleading... ssl.au3 is the old way of sending out emails. It sends the command directly to the cmd window. SMTP_ssl_V2 uses the new beta way of sending commands to a command window. You don't need both, they are completely separate scripts, but they do require _Base64.

So you never get the <RECV> CONNECTED message in the command trace window? This code is supposed to send an email out without any user intervention. the command trace window is there so you can see what is happening.

Try running the older version of the code: ssl.au3, let me know how that works. You can comment out this line in the old version

;WinMove(@SystemDir & "\cmd.exe", "", @DesktopWidth, @DesktopHeight)
It should be on line 65 or so. Tell me if a command window stays open or just flashes. It should stay open, if it doesn't then that means that autoit is sending the cmd window the wrong info. Check the $SSL_Exe_loc and make sure that points to the correct file. Do all of this in ssl.au3 and run ssl.au3

Let me know if you find the problem... if not I'm not sure what could be wrong.

Edited by mikeytown2

Share this post


Link to post
Share on other sites

I should apologize for my naming convention, its a little misleading... ssl.au3 is the old way of sending out emails. It sends the command directly to the cmd window. SMTP_ssl_V2 uses the new beta way of sending commands to a command window. You don't need both, they are completely separate scripts, but they do require _Base64.

So you never get the <RECV> CONNECTED message in the command trace window? This code is supposed to send an email out without any user intervention. the command trace window is there so you can see what is happening.

Try running the older version of the code: ssl.au3, let me know how that works. You can comment out this line in the old version

;WinMove(@SystemDir & "\cmd.exe", "", @DesktopWidth, @DesktopHeight)
It should be on line 65 or so. Tell me if a command window stays open or just flashes. It should stay open, if it doesn't then that means that autoit is sending the cmd window the wrong info. Check the $SSL_Exe_loc and make sure that points to the correct file. Do all of this in ssl.au3 and run ssl.au3

Let me know if you find the problem... if not I'm not sure what could be wrong.

Hi Mikey!

Thanx for help once again (:o sounds repetitive though)

I tried what u said. But now the command window opened and diplayed a msg

Loading 'screen' into random state - done

And it closed after about 5-6 seconds. However, the Command Tracer Box displayed nothing :geek:

Dunno what could be the problem.

P.S.: I still think it's my Univ's firewall, that might be causing the trouble.


I believe we should all pay our tax with a smile. I tried - but they wanted cash!

Share this post


Link to post
Share on other sites

Run this code and let me know what the cmd window says

Opt("SendKeyDelay", 0)

$SSL_Exe_loc = "C:\OpenSSL\bin\openssl.exe"
$SMTP_Server = "smtp.gmail.com"
$SMTP_Port = "465"

Run($SSL_Exe_loc)
WinWait($SSL_Exe_loc)
BlockInput(1)
WinActivate($SSL_Exe_loc)
WinWaitActive($SSL_Exe_loc)
Send('s_client -connect ' & $SMTP_Server & ':' & $SMTP_Port & '{ENTER}')
BlockInput(0)

You can also open up ethereal and have it capture the packets right when your trying to connect. Use a filter of tcp.port eq 465

Have you tried connecting to gmail using an email client like thunderbird?

If your firewall blocks outgoing packets on port 465 then i can't help you i'm affraid.

Share this post


Link to post
Share on other sites

Run this code and let me know what the cmd window says

Opt("SendKeyDelay", 0)

$SSL_Exe_loc = "C:\OpenSSL\bin\openssl.exe"
$SMTP_Server = "smtp.gmail.com"
$SMTP_Port = "465"

Run($SSL_Exe_loc)
WinWait($SSL_Exe_loc)
BlockInput(1)
WinActivate($SSL_Exe_loc)
WinWaitActive($SSL_Exe_loc)
Send('s_client -connect ' & $SMTP_Server & ':' & $SMTP_Port & '{ENTER}')
BlockInput(0)
Hi Mikey!

I ran the aforementioned code and got this:

OpenSSL> s_client -connect smtp.gmail.com:465
Loading 'screen' into random state - done
gethostbyname failure
connect:errno=11001
error in s_client
OpenSSL>

You can also open up ethereal and have it capture the packets right when your trying to connect. Use a filter of tcp.port eq 465

I will look into ethereal, but I think it's my Univ's firewall.

Have you tried connecting to gmail using an email client like thunderbird?

No, the Univ's firewall doesn't allow us to use email clients. I do use YPoPs! for POPing Yahoo Mails in my email client. But no SMTP! :geek:

If your firewall blocks outgoing packets on port 465 then i can't help you i'm affraid.

Yeah, now I am pretty sure it's my Univ's firewall that is the real culprit. And you have already helped me a lot!! Thanks mate for being so patient. :o

I believe we should all pay our tax with a smile. I tried - but they wanted cash!

Share this post


Link to post
Share on other sites

Hi Mikey!

I ran the aforementioned code and got this:

OpenSSL> s_client -connect smtp.gmail.com:465
Loading 'screen' into random state - done
gethostbyname failure
connect:errno=11001
error in s_client
OpenSSL>
That means that the DNS server is blocking anything with smtp or pop in it most likely... i did a DNS lookup of smtp.gmail.com and i got this IP

66.249.83.111

So in the code above run it again but change this

$SMTP_Server = "66.249.83.111"

Let me know if anything works... they could have the port blocked as well.

Share this post


Link to post
Share on other sites

#19 ·  Posted (edited)

Your script works great, Mikey! I've made a send-mail script using stdin/stdout automation, based on your work.

It only needs to invoke openssl.exe and doesn't need to kill the child process when email is sent normally. Also I consider that StdinWrite() is more reliable than Send().

Those who would like to try my script must use OpenSSL for Cygwin instead of OpenSSL for Windows. Because of a bug in the Windows build of OpenSSL (of both 0.9.7i & 0.9.8a), s_client command will NOT respond to StdinWrite() until the user interactively press at lease one key when the console window is active, which makes the automation fail. No such problem with the Cygwin build of OpenSSL (of 0.9.8a, as I've tested). Currently, it might be the only version that can be used for stdin/stdout automation of s_client command on Win32 platform.

Download Cygwin here: http://www.cygwin.com/

You need to manually choose OpenSSL component when you run the online setup program.

The script should be put in the bin directory of Cygwin, for example, C:\Cygwin\bin. Use SciTE's Beta Run command to see the console outputs. Needs beta version of AutoIt 3.

$FromAddress = "yourusername@gmail.com"
$ToAddress = "somebody@somewhere.com"
$FromName = "yourname"
$Subject = "AutoIt Gmail Automation Test (with body & dots)"
$Body = "This is a test of Gmail automation." & @CRLF & "Just see what happen!" & @CRLF & "...when this line begins with dots!"
$Charset = "US-ASCII"
$Login = "<base64 encoded username>"
$Phase = "<base64 encoded password>"
$SmtpServer = "smtp.gmail.com"
$SmtpPort = "465"
; Must use Cygwin OpenSSL in order to implement stdin automation; the Windows build has a bug which makes StdinWrite() fail.
$OpensslPath = '"' & @ScriptDir & '\openssl.exe" s_client -quiet -connect ' & $SmtpServer & ':' & $SmtpPort
$WorkingDir = @ScriptDir

Dim $Conditions[9], $Actions[9], $Masked[9]
$Conditions[0] = '220 '
$Actions[0] = 'ehlo AutoIt3'
$Conditions[1] = '250 '
$Actions[1] = 'AUTH LOGIN'
$Conditions[2] = '334 '
$Actions[2] = $Login
$Masked[2] = 1; Masks username for output
$Conditions[3] = '334 '
$Actions[3] = $Phase
$Masked[3] = 1; Masks password for output
$Conditions[4] = '235 '
$Actions[4] = 'MAIL FROM: <' & $FromAddress & '>'
$Conditions[5] = '250 '
$Actions[5] = 'RCPT TO: <' & $ToAddress & '>'
$Conditions[6] = '250 '
$Actions[6] = 'DATA'
$Conditions[7] = '354 '
$Actions[7] =   "From:" & $FromName & "<" & $FromAddress & ">" & @CRLF & _
                "To:" & "<" & $ToAddress & ">" & @CRLF & _
                "Subject:" & $Subject & @CRLF & _
                "Mime-Version: 1.0" & @CRLF & _
                "Content-Type: text/plain; charset=" & $Charset & @CRLF & _
                @CRLF & StringRegExpReplace($Body, "(\N{1,2}\.)", "\1.") & @CRLF & _
                @CRLF & "."
$Conditions[8] = '250 '
$Actions[8] = 'QUIT'

$State = 0
$StdoutLastLen = 0
$StdoutLen = 0
$StderrLastLen = 0
$StderrLen = 0
$Timeout = 20000

Opt('RunErrorsFatal', False)
$OpensslPid = Run($OpensslPath, $WorkingDir, @SW_HIDE, 1+2+4)

If @error Then
    ConsoleWrite('[Warning] Failed to run OpenSSL.' & @LF)
    Exit
EndIf

$Timer = TimerInit()

While ProcessExists($OpensslPid)
; Use PEEK mode to avoid hanging
    $StderrLen = StderrRead($OpensslPid, 0, 1)
    $StderrAll = StderrRead($OpensslPid, -1, 1)
    $Stderr = StringMid($StderrAll, $StderrLastLen+1, $StdoutLen-$StderrLastLen)
    If $StderrLen > $StderrLastLen Then
        ConsoleWrite($Stderr)
    EndIf
    $StderrLastLen = $StderrLen
    
    $StdoutLen = StdoutRead($OpensslPid, 0, 1)
    $StdoutAll = StdOutRead($OpensslPid, -1, 1)
    $Stdout = StringMid($StdoutAll, $StdoutLastLen+1, $StdoutLen-$StdoutLastLen)
    If $StdoutLen > $StdoutLastLen Then
        ConsoleWrite($Stdout)
    EndIf
    $StdoutLastLen = $StdoutLen
    
    If $State < UBound($Conditions) And $State < UBound($Actions) Then
        If _StringLineBegin($Stdout, $Conditions[$State]) Then
            StdInWrite($OpensslPid, $Actions[$State] & @CRLF)
            If $Masked[$State] = 1 Then
                ConsoleWrite('<masked>' & @CRLF)
            Else
                ConsoleWrite($Actions[$State] & @CRLF)
            EndIf
            $State += 1
            $Timer = TimerInit()
        EndIf
    EndIf
    
    If TimerDiff($Timer) > $Timeout Then
        ConsoleWrite('[Warning] Error or timeout. Quit.' & @LF)
        ExitLoop
    EndIf
    
    Sleep(1)
Wend

Func _StringLineBegin($v_EntireStr, $v_SubStr)
    If StringLeft($v_EntireStr, StringLen($v_SubStr)) = $v_SubStr Then
        Return 1
    ElseIf StringRegExp($v_EntireStr, '\N{1,2}(' & _RegExpEscape($v_SubStr) & ')', 0) Then
        Return 1
    Else
        Return 0
    EndIf
EndFunc

Func _RegExpEscape($v_Str)
    Local $t_Result
    $t_Result = StringReplace($v_Str, '\', '\\')
    $t_Result = StringReplace($t_Result, '+', '\+')
    $t_Result = StringReplace($t_Result, '*', '\*')
    $t_Result = StringReplace($t_Result, '.', '\.')
    $t_Result = StringReplace($t_Result, '?', '\?')
    $t_Result = StringReplace($t_Result, '|', '\|')
    $t_Result = StringReplace($t_Result, '[', '\[')
    $t_Result = StringReplace($t_Result, ']', '\]')
    $t_Result = StringReplace($t_Result, '(', '\(')
    $t_Result = StringReplace($t_Result, ')', '\)')
    $t_Result = StringReplace($t_Result, '{', '\{')
    $t_Result = StringReplace($t_Result, '}', '\}')
    Return $t_Result
EndFunc

Func OnAutoItExit()
    If ProcessExists($OpensslPid) Then ProcessClose($OpensslPid)
EndFunc
Edited by CatchFish

Share this post


Link to post
Share on other sites

CatchFish

Awesome stuff! i all ready have cygwin installed so i can use x windows. I'll test out your code soon, it looks good. btw check out my base64 thread. I've updated the INetSmtpMail udf so you can send email directly to the mx server which i though was fairly cool. no need for a smtp server anymore!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0