Open the default program for sending email messages

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 otherwisePublic 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("[email protected]") 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&, 1End Sub' how to use:SendMail "[email protected]", "SendMail Test", "The function works!!!", _    "[email protected], [email protected]"

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.

See also  The Art of AI-Generated Meeting Minutes

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist