Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB4/32,VB5,VB6
Expertise: beginner
Jan 8, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Open the default program for sending email messages

The ShellExecute API function recognizes email addresses if they are prefixed by the "mailto:" prefix, and correctly run the default program for sending email messages (e.g. Outlook). This lets you open a window for sending an email and automatically fill the address field. Here's a wrapper routine that encapsulates the low-level details:

Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
    (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, _
    ByVal lpParameters As String, ByVal lpDirectory As String, _
    ByVal nShowCmd As Long) As Long

' Open the default program for sending email messages
' Returns True if successful, False otherwise

Public Function OpenEmailProgram(ByVal EmailAddress As String) As Boolean
    Dim res As Long
    res = ShellExecute(0&, "open", "mailto:" & EmailAddress, vbNullString, _
        vbNullString, vbNormalFocus)
    OpenEmailProgram = (res > 32)
End Function
You should always check the return value of the function, in case no program has been registered on the machine:

If Not OpenEmailProgram("username@domain.com") Then
    MsgBox "Unable to run the email program"
End If
UPDATE: It turns out that you can even provide the contents for other mail fields, by passing additional values on the URL. The following updated version of the routine above supports a subject, the body of the message, a CC mail address and a BCC address. All these added arguments are optional:

Sub OpenEmailProgram(sDest As String, Optional sSubject As String, _
    Optional sBody As String, Optional sCC As String, Optional sBCC As String)
    ShellExecute 0, vbNullString, "mailto:" & sDest & "?subject=" & sSubject & _
        "&body=" & sBody & "&CC=" & sCC & "&BCC=" & sBCC, 0&, 0&, 1
End Sub

' how to use:
SendMail "mbellinaso@vb2themax.com", "SendMail Test", "The function works!!!", _
    "fbalena@vb2themax.com, desposito@vb2themax.com"
UPDATE: This approach has one limitation under Windows NT4, whose Shell function can pass parameters longer than 260 characters and can therefore truncate long mail addresses. Unfortunately there isn't any simple workaround (this problem has been solved in Windows 2000, though). Thanks to John Tenney that drew our attention on the KB Article mentioned below.
Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date