Adam Caudill

Security Leader, Researcher, Developer, Writer, & Photographer

Get Default Mail Client

This post was imported from an old blog archive, and predates the creation of AdamCaudill.com.

This is another code example made by request for a forum member, it simply retrieves the default value from HKEY_CLASSES_ROOT\mailto\shell\open\command which should be the default mail client.

Option Explicit

Private Declare Function RegOpenKey Lib "advapi32.dll" Alias "RegOpenKeyA" ( _
    ByVal hKey As Long, _
    ByVal lpSubKey As String, _
    phkResult As Long _
) As Long

Private Declare Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" ( _
    ByVal hKey As Long, _
    ByVal lpValueName As String, _
    ByVal lpReserved As Long, _
    lpType As Long, _
    lpData As Any, _
    lpcbData As Long _
) As Long

Private Declare Function RegCloseKey Lib "advapi32.dll" ( _
    ByVal hKey As Long _
) As Long

Private Const REG_SZ = 1
Private Const ERROR_SUCCESS = 0&
Private Const HKEY_CLASSES_ROOT = &H80000000

Public Function GetDefaultMailClient() As String
Dim lngResult As Long
Dim lngKeyHandle As Long
Dim lngValueType As Long
Dim lngBufferSize As Long
Dim strBuffer As String

    lngResult = RegOpenKey(HKEY_CLASSES_ROOT, "mailto\shell\open\command", lngKeyHandle)
    lngResult = RegQueryValueEx(lngKeyHandle, "", 0, lngValueType, ByVal 0, lngBufferSize)
    If lngValueType = REG_SZ Then
        strBuffer = String(lngBufferSize, " ")
        lngResult = RegQueryValueEx(lngKeyHandle, "", 0, 0, ByVal strBuffer, lngBufferSize)
        If lngResult = ERROR_SUCCESS Then
            If (InStr(strBuffer, Chr$(0))) > 0 Then
                GetDefaultMailClient = Left(strBuffer, (InStr(strBuffer, Chr$(0))) - 1)
            Else
                GetDefaultMailClient = strBuffer
            End If
        End If
    End If
End Function

Adam Caudill