Android Code Snippet Sending HTML Email via SMTP

Hi Everyone.
In my last project I needed an email function. I decided to use the NET Lib to send mails via SMTP.
If you use messages with attachments, there is nothing special to discuss, but without attachments it is a little bit tricky.
The reason for attention is the SMPT/MIME Type "Quoted-Printable, or QP encoding"
which treats an equal sign plus 2 following characters as control characters for mails
without attachments
.
(ref. http://en.wikipedia.org/wiki/Quoted-printable)
In this code snippet you can see how to handle that.

B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A SMTP Snippet
    #VersionCode: 1
    #VersionName: 1.0.0
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: landscape
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

' DONT FORGET Manifest ****
' AddApplicationText(<activity android:name="de.amberhome.objects.preferenceactivity"/>)
' DONT FORGET Manifest ****

    Dim Manager As AHPreferenceManager
    Dim Screen As AHPreferenceScreen
    Dim SMTP As SMTP

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

    Private BtnPrefs As Button
    Private BtnSend As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("1")
If FirstTime Then

    CreatePreferenceScreen

    If Manager.GetAll.Size = 0 Then

        ' SMTP defaults
        Manager.SetString("EmailBody", "000") ' def plain
        Manager.SetString("EmailSenderAddress", "")
        Manager.SetString("EmailAdr", "")
        Manager.SetString("EmailAccountAdr", "")
        Manager.SetString("EmailPort", "25")
        Manager.SetString("EmailAccountName", "")
        Manager.SetString("EmailPassword", "")
        Manager.SetString("EmailAuthMethod", "001")
        Manager.SetBoolean("EmailUseSSL",False)
        Manager.SetBoolean("EmailTLSMode",False)
    End If

End If

#If Testing
ForEmailTest
#end if

End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
Sub CreatePreferenceScreen

    Screen.Initialize("Settings", "")
    'create category
    Dim cat1 As AHPreferenceCategory
    Dim EmailScreen As AHPreferenceScreen

EmailScreen.Initialize ("Account","SMTP Account setup")
'** Email HTML or PLAIN content
    Dim map3 As Map
    map3.Initialize
    map3.Put("000", "PLAIN content")
    map3.Put("001", "HTML content")
    EmailScreen.AddList2("EmailBody", "Email Body", "Html or Plain Text", "000", "", map3)

'** Sender Address
'  DONT DARE TO MISUSE !!! ;-)
    EmailScreen.AddEditText2("EmailSenderAddress", "FROM Address", "not neccessary" , " ", 1 , False, True, "")
'** Send TO Email Address
    EmailScreen.AddEditText2("EmailAdr", "to Address", "Send to Emailaddress" , " ", 1 , False, True, "")
'** SMTP Account Address
    EmailScreen.AddEditText2("EmailAccountAdr", "SMTP Address", "Account address" , "", 1 , False, True, "")
'** SMTP Port (25)
    EmailScreen.AddEditText2("EmailPort", "SMTP Port", "Default 25" , "25", 2, False, True, "")
'** SMPT Email Account Name
    EmailScreen.AddEditText2("EmailAccountName", "Account Name", "Your Account Name" , "", 1 , False, True, "")
'** SMPT Email Account Password
    EmailScreen.AddPassword("EmailPassword","Account Password","Your SMTP Account Password","","")
'** SMPT Email Authentication Method
    Dim map2 As Map
    map2.Initialize
    map2.Put("000", "AUTH_CRAM_MD5")
    map2.Put("001", "AUTH_LOGIN")
    map2.Put("002", "AUTH_PLAIN")
    EmailScreen.AddList2("EmailAuthMethod", "Authentication Method", "Default AUTH_LOGIN", "001", "", map2)
'** SMPT Use SSL
    EmailScreen.AddCheckBox("EmailUseSSL", "Use SSL", "SSL enabled", "SSL disabled", False, "")
'** SMPT Use TLS Mode
    EmailScreen.AddCheckBox("EmailTLSMode", "Use TLS Mode", "TLS enabled", "TLS disabled", False, "")

cat1.Initialize("Email Options")
'****
    cat1.AddPreferenceScreen (EmailScreen,"")
    Screen.AddPreferenceCategory(cat1)



End Sub

Sub BtnPrefs_click

  CreatePreferenceScreen
  StartActivity(Screen.CreateIntent)

End Sub
Sub  BtnSend_click

ToastMessageShow("Email function request "  , True)


Dim EmailSenderAddress As String = Manager.GetString ("EmailSenderAddress")
Dim EmailAdr As String = Manager.GetString ("EmailAdr")
Dim EmailAccountAdr As String = Manager.GetString ("EmailAccountAdr")
Dim EmailPort As Int = Manager.GetString ("EmailPort")
Dim EmailAccountName As String  = Manager.GetString ("EmailAccountName")
Dim EmailPassword As String  = Manager.GetString ("EmailPassword")
Dim EmailAuthMethod As String  = Manager.GetString ("EmailAuthMethod")
Dim EmailUseSSL As Boolean  = Manager.GetBoolean  ("EmailUseSSL")
Dim EmailTLSMode As Boolean  = Manager.GetBoolean  ("EmailTLSMode")
Dim EmailBody As String  = Manager.Getstring  ("EmailBody")

SMTP.Initialize(EmailAccountAdr, EmailPort, EmailAccountName, EmailPassword, "SMTP")
SMTP.UseSSL = EmailUseSSL
If EmailSenderAddress <> "" Then
    SMTP.Sender = EmailSenderAddress
End If

Select EmailAuthMethod
    Case "000"
        SMTP.AuthMethod = SMTP.AUTH_CRAM_MD5
    Case "001"
        SMTP.AuthMethod = SMTP.AUTH_LOGIN
    Case "002"
        SMTP.AuthMethod = SMTP.AUTH_PLAIN
    Case Else
End Select

SMTP.StartTLSMode = EmailTLSMode

SMTP.To.Add(EmailAdr)
SMTP.Subject = "B4A SMTP Snippet"

Dim BodyTemp As String
'Dim StrUtil As StringUtils
Select EmailBody
    Case "000"
        SMTP.HtmlBody = False

        SMTP.Body = "This is your Email Body Text" _
        & Chr(10) & Chr(10) & _
        "Have a nice day" & Chr(10) & _
        "Your Support Team"

    Case "001"
        SMTP.HtmlBody = True

        BodyTemp = File.ReadString(File.DirAssets, "EMAIL_TEST.htm")

' SEE    http://en.wikipedia.org/wiki/Quoted-printable
' DONT Replace when using Attachments
        BodyTemp = BodyTemp.Replace ("=","=3D")

        ' change Background color to #e3efff
        BodyTemp = BodyTemp.Replace ("$001","#e3efff")
        SMTP.Body = BodyTemp

    Case Else
End Select


'    SMTP.AddAttachment(File.DirRootExternal, "somefile")

SMTP.Send


End Sub
Sub SMTP_MessageSent(Success As Boolean)
'    Log(Success)
    If Success Then
        ToastMessageShow("Youre Message was sent successfully", True)
    Else
'        ToastMessageShow("Error sending message", True)
        Msgbox(LastException.Message,"Email Sending Problem")
    '    Log(LastException.Message)
    End If
End Sub
Sub ForEmailTest

        ' SMTP defaults
        Manager.SetString("EmailSenderAddress", "[email protected]")
        Manager.SetString("EmailAdr", "[email protected]")
        Manager.SetString("EmailAccountAdr", "192.168.216.22")
        Manager.SetString("EmailPort", "25")
        Manager.SetString("EmailAccountName", "[email protected]")
        Manager.SetString("EmailPassword", "")
        Manager.SetString("EmailAuthMethod", "001")
        Manager.SetBoolean("EmailUseSSL",False)
        Manager.SetBoolean("EmailTLSMode",False)

ToastMessageShow("TRON TEST EMAIL SETTIGNS"  , True)

End Sub

Example from an "undelivered" Mail Server email file (with substitutions: = to =3D )
B4X:
Received: from spooler by localhost (Mercury/32 v4.62); 26 Aug 2014 22:30:45 +0200
X-Envelope-To: <[email protected]>
Return-path: <[email protected]>
Received: from 192.168.216.130 (192.168.216.130) by localhost (Mercury/32 v4.62) with ESMTP ID MG000016;
  26 Aug 2014 22:30:38 +0200
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: quoted-printable
From: [email protected]
To: [email protected]
Subject: B4A SMTP Snippet

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns=3D"http://www.w3.org/1999/xhtml" xml:lang=3D"en" lang=3D"en" dir=3D"ltr">
<head>
    <title>Email TEst</title>

    <!-- Contents -->
    <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3Diso-8859-1" />
    <meta http-equiv=3D"Content-Language" content=3D"en" />

</head>
<body bgcolor=3D"#e3efff">
        <div align=3D"left">
            <h1><strong>Hello Friends.</strong></h1>
            <p><strong><span class=3D"ff2 fc0 fs10 ">This is a HTML Email contents </span><span class=3D"ff1 fc0 fs10 "><br /><br /><br />
                    </strong></p>
            <p><strong><span class=3D"ff2 fc0 fs10 ">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</span><span class=3D"ff1 fc0 fs10 "><br />
                    </strong></p>
        </div>
    </body>
</html>

Example Email with Attachment (NO need to replace: = to =3D ) !
B4X:
Received: from spooler by localhost (Mercury/32 v4.62); 27 Aug 2014 19:31:06 +0200
X-Envelope-To: <[email protected]>
Return-path: <[email protected]>
Received: from 192.168.216.130 (192.168.216.130) by localhost (Mercury/32 v4.62) with ESMTP ID MG000008;
  27 Aug 2014 19:30:58 +0200
Content-Type: multipart/mixed; boundary="asdasdwdwqd__HV_qwdqwdddwq"
From: [email protected]
To: [email protected]
Subject: B4A SMTP Snippet

--asdasdwdwqd__HV_qwdqwdddwq
Content-Type: text/html; charset="utf-8"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
    <title>Email TEst</title>

    <!-- Contents -->
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <meta http-equiv="Content-Language" content="en" />

</head>
<body bgcolor="#e3efff">
        <div align="left">
            <h1><strong>Hello Friends.</strong></h1>
            <p><strong><span class="ff2 fc0 fs10 ">This is a HTML Email contents </span><span class="ff1 fc0 fs10 "><br /><br /><br />
                    </strong></p>
            <p><strong><span class="ff2 fc0 fs10 ">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</span><span class="ff1 fc0 fs10 "><br />
                    </strong></p>
        </div>
    </body>
</html>

--asdasdwdwqd__HV_qwdqwdddwq
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="b64gif.b64"

UjBsR09EZGhNQUF3QVBBQUFBQUFBUC8vL3l3QUFBQUFNQUF3QUFBQzhJeVBxY3Z0M3dDY0RraUxj
N0MwcXd5R0hoU1dwalF1NXlxbUNZc2FweXV2VVVsdk9ObU9adGZ6Z0Z6QnlUQjEwUWd4T1IwVHFC
UWVqaFJOek9ma1ZKKzVZaVVxclhGNVk1bEtoL0RldU5jUDV5TFdHc0VidExpT1NwYS9UUGc3SnBK
SHh5ZW5keldUQmZYMGN4T25LUGpnQnppNGRpaW5XR2RrRjhramRmbnljUVpYWmVZR2VqbUpsWmVH
bDlpMmljVnFhTlZhaWxUNkY1aUo5MG02bXZ1VFM0T0swNU0wdkRrMFE0WFV0d3ZLT3pyY2QzaXE5
dWlzRjgxTTFPSWNSN2xFZXd3Y0xwN3R1Tk5rTTN1Tm5hM0YySlFGbzk3VnJpeS9YbDQvZjFjZjVW
V3pYeXltN1BIaGh4NGRiZ1lLQUFBNw==


052.png



For the account parameter maintenance I used the AHPreference lib.

I attached the code zip file.

Maybe there will be an option to influence the header of SMTP transmissions in the future. ;)
At the moment I see no options to send multiparted Mails (for sending embedded bitmaps)
see http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html and http://mobiledevtuts.com/android/android-sdk-smtp-email-tutorial/
greets Jens
 

Attachments

  • HtmlEmail.zip
    9.4 KB · Views: 579
Last edited:
Top