B4A Library New Net library - Android FTP, SMTP and POP3

Status
Not open for further replies.
The Net library supports FTP, SMTP and POP3 protocols. This library replaces the FTP library. Both regular connections and SSL connections are supported.
SMTP - Allows to directly connect to SMTP mail servers and send mails, including Html messages and attachments.
POP3 - Allows to directly connect to POP3 mail servers and download messages. Currently the messages are not parsed. The raw string is returned. You can use MailParser class to parse the raw messages.

Installation instructions:
- Download the attach file.
- Copy Net.xml and Net.jar to the additional libraries folder. Make sure that there are no older copies in the internal libraries folder.

V1.81 - latest version
V1.80 - SMTP, POP and FTP can be configured to use a custom trust manager. This allows accepting invalid certificates.

V1.77 - New Sender.MailFrom field. Allows setting the mail address that is sent with the MAIL command. By default it is the same as the Username field.

V1.75 - Adds a configurable timeout parameter - FTP.TimeoutMs. Default timeout is set to 60000 (60 seconds).

V1.70 - Adds support for calling with Wait For: https://www.b4x.com/android/forum/threads/b4x-net-library-ftp-smtp-pop-with-wait-for.84821/
SMTP.AdditionalHeaders map. Allows adding headers to the messages.

V1.63 - Fixes an issue with SMTP mails with attachments. The closing boundary was previously missing.
V1.62 - Fixes an issue with SMTP in StartTLS mode.
V1.61 - Fixes an issue in SMTP related to the content encoding not being set in multipart messages.

V1.60 - New method: FTP.AppendFile. Similar to UploadFile. Appends the data to an existing file if such exists. It sends the APPE FTP command.

V1.53 - Fixes an issue with FTP.CloseNow and SSL connections.

V1.52 - Adds support for different types of authentication methods (SMTP): http://www.b4x.com/android/forum/th...d-ftp-smtp-and-pop3.10892/page-11#post-232432

V1.51 is released. Fixes an issue with FTP over SSL explicit mode.

V1.50 is released. See this link: http://www.b4x.com/android/forum/th...d-ftp-smtp-and-pop3.10892/page-10#post-231145

V1.37 is released. This version removes the automatic escaping of '=' characters in SMTP messages. To implement it in your code you should write:
B4X:
SMTP.Body = SMTP.Body.Replace("=", "=3D")


V1.35 is released. This version adds support for STARTTLS mode.
Unlike UseSSL mode the connection is "upgraded" to a secured connection only after the client sends the STARTTLS command.
Most of the popular smtp servers support this mode, usually on port 587.

B4X:
Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
      smtpClient.Initialize("smtp.gmail.com", 587, "[email protected]", "yyy", "SmtpClient")
      smtpClient.StartTLSMode = True
   End If
End Sub
 

Attachments

  • Net.zip
    189.1 KB · Views: 3,003
Last edited:

Kwame Twum

Active Member
Licensed User
Longtime User
so Erel, isn't there anything I can do about it? :)
Or I'll have to work on a different server...
 
Last edited:

sorex

Expert
Licensed User
Longtime User
Erel,

How come this library is not included in the B4A install?

It's an "official one by you"
 

sorex

Expert
Licensed User
Longtime User
ok, I can live with that.

it's just confusing to have net and network.

for example I added network and started typing

dim ftp as ftp

and wondered why it resulted in an error, then I spotted that net was a replacement for the ftp lib
and the ftp lib was an additional/seperate lib than the network lib.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
V1.50 is released. It adds support for FTP Over SSL explicit mode (implicit mode was already supported by setting UseSSL to true).

It also includes a new object type named CustomTrustManager. CustomTrustManager allows you to load certificates from files and also to create a trust manager that accepts all certificates without checking them.

For now it can only be used with FTP.

To use it you should initialize a CustomTrustManager object and then set it with FTP.SetCustomSSLTrustManager.
 

Hubert Brandel

Active Member
Licensed User
Longtime User
Hi,
with the SSL and TLS I get an TimeOut Error:
B4X:
Try to send on: 587, SSL: false, TLS: true
TO: true count: 1 = [email protected]
After Send ...
SMTP send: false
java.net.SocketTimeoutException: Connection timed out
with 25 and both ssl and tls vars to false I get this
B4X:
java.lang.RuntimeException:
Empty writer returned: 503 Bad sequence of commands.
You must specify the recipients of a message before you can send it
so it looks like the DEBUGGER MODE could send the email, but the SMTP Server does not response on SSL / TSL ...
and the responce on port 25 is an error message from the server ... is this right ?

But what does he want to tell me with the bad sequence ?

B4X:
'Activity module
Sub Process_Globals
    ...
    Dim sDir As String = File.DirRootExternal     ' file attachement from ...
    Dim sFile As String = "HB-PDF.pdf"            ' name ...
    Dim sTo As String = "[email protected]"
    ' email über SMTP Server ... hierfür braucht man eine Internetverbindung und Klaus sollte eine eMail-Sendeadresse auf seinem Server anlegen.
    Dim SMTP As SMTP
    Dim sServer As String = "mail.server.de"  ' the SMTP Server
    Dim sSender As String = "[email protected]" ' each app has its own eMailAdress to send from ...
    Dim sFrom As String = sSender
    Dim sPW As String = "..." ' the right password
    Dim iPort As Int     = I want to change this later in the APP

End Sub

' normaly this code should be here ...

Sub Activity_Create(FirstTime As Boolean)   
   If FirstTime Then
     Label1.Text = "eMail an: " & sTo
     Port25.Checked = True
     iPort = 25
     SMTP.Initialize(sServer, iPort, sFrom,sPW,"SMTP")
     SMTP.StartTLSMode = False
     SMTP.UseSSL = False
   End If    
End Sub

but than I can't change the port later in the app, am I right ?
so I removed the init from activity_create to the button_click event ...

B4X:
Sub Send_Click
   If File.Exists(sDir,sFile) Then ' no file, no eMail
     ToastMessageShow("PDF senden (" & iPort & ")...",False) ' this shows the right port
     SMTP.Initialize(sServer, iPort, sFrom, sPW, "SMTP" ) ' look good in debugger
     If iPort = 25 Then
        SMTP.UseSSL = False
        SMTP.StartTLSMode = False
     Else
       If iPort = 465 Then
         SMTP.UseSSL = True
         SMTP.StartTLSMode = False
        End If   

       If iPort = 587 Then
         SMTP.UseSSL = False
         SMTP.StartTLSMode = True
        End If   
     End If   
     Log("Try to send on: " & iPort & ", SSL: " & SMTP.UseSSL & ", TLS: " & SMTP.StartTLSMode )
     
     SMTP.Sender = sSender ' no change if I remove this line 
     SMTP.To.Add(sTo) 
     Log("TO: " & SMTP.To.IsInitialized & " count: " & SMTP.To.Size & " = " & SMTP.To.Get(0) ) ' The log say, that I have 1 TO adress and it is right.
     SMTP.Subject = "Test eMail mit PDF Anhang"
     SMTP.Body = "Diese PDF habe ich gerade vom Smartphone erzeugt ;-) "
     SMTP.AddAttachment(sDir,sFile)
     SMTP.Send
     Log("After Send ...")     
   Else
     ToastMessageShow("PDF fehlt !",False)
   End If
End Sub

Sub SMTP_MessageSent(Success As Boolean)
   Log("SMTP send: " & Success )
     If Success Then
     ToastMessageShow("PDF wurde versandt !",True)
   Else
    ToastMessageShow("eMail Fehler !",True)
     Log(LastException.Message)
   End If   
End Sub

the log says this with 25 (no SSL/TLS)

B4X:
...Try to send on: 25, SSL: false, TLS: false
TO: true count: 1 = [email protected]
After Send ...
SMTP send: false
java.lang.RuntimeException: Empty writer returned: 
503 Bad sequence of commands. You must specify the recipients of a message before you can send it

I have cut & paste the code from some examples and could not find what is missing ;-(

PS: NET 1.50 ... just loaded into the ExtraLib SubDir.
 

Hubert Brandel

Active Member
Licensed User
Longtime User
very strange, if I use my own GMX.DE email account with ...
iPort = 465
SMTP.UseSSL = True
SMTP.StartTLSMode = False

than the eMail is send correct and true will come back.
With ...
iPort = 587
SMTP.UseSSL = False
SMTP.StartTLSMode = True

same error 503 ...
 

Hubert Brandel

Active Member
Licensed User
Longtime User
I found a SMTP Error PDF with this info:

503 now means that your server request a authentication ... but still use 25.
Is there a setting to tell SMTP-Lib to authenticate ?
 

warwound

Expert
Licensed User
Longtime User
I haven't checked it.

I've been asked whether i can update NetExtras so it is based on Net version 1.50 instead of Net version 1.20 which is rather an old version now.
I seem to remember Erel sent me the Net library source code Feb/March last year so that i could modify it.

So can i ask Erel if it's possible to do the same again?
Can i have a copy of the Net library version 1.50 source so i can create the modified FTP and SMTP objects?

Thanks.

Martin.
 

Hubert Brandel

Active Member
Licensed User
Longtime User
It will always try to authenticate. Are you sure that the server expects an SSL connection?
This server (with the 503 message and 25 as port) does NOT want a SSL connection, because normaly I use a Win32 bit EXE as CGI-EXE and send with the "ASINET" LIB from my win32 bit compiler. This LIB does not support SSL or TLS, just login with name and password. Its a hosteurope web server.
B4X:
*----------------------------------------------------------------------------------------
Function SendAsinet(aEmpfaenger,cBetreff,cText,cProgPfad,aAttachFile,cAntwortAdresse) ' my function
  ... 
  LOCAL oSmtp  := SMTPClient():new( GetSmtpServer(),,, oLog, 2 )
  LOCAL oSender  := MailAddress():new( "[email protected]" )
  LOCAL oMail  := MIMEMessage():new()

  oMail:setFrom  ( oSender  ) // "[email protected]"
  oMail:setSubject  ( cBetreff  ) // "Test eMail ..."
  oMail:setMessage  ( cText  ) // just the body text
  aeval(aEmpfaenger, {|cEmp| oMail:addRecipient(MailAddress():new(cEmp) ) }) ' adds all TO adresses
  oMail:addHeader( "Date", TimeStampSMTP() ) ' need to correct an error with date 
  if ! aAttachFile = NIL
     aeval(aAttachFile, {|cFile| oMail:attachFile( cFile ) })
  endif

  IF oSmtp:connect( sUserName, sPassword ) ' fix from a ini file
     IF oSmtp:send( oMail )
         lOK := .t.
         ? "Message sent"
     ELSE
         ? "Unable to deliver message"
     ENDIF
     oSmtp:disconnect()
  ELSE
     ? "Unable to connect to mail server"
  ENDIF
RETURN lOK

this LIB just connect with (sUserName, sPassword), no PORT (means standard), no SSL / TLS ... in both cases this server does not responde on SSL / TLS connections, but give this 503 Error back with 25 (try) connection.
 

enemotrop

Member
Licensed User
Longtime User
Is it possible to append a line to a text file using this library? Like using the APPE ftp command...


APPE
Syntax: APPE remote-filename
Append data to the end of a file on the remote host. If the file does not already exist, it is created. This command must be preceded by a PORT or PASV command so that the server knows where to receive data from.
 
Status
Not open for further replies.
Top