Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleStart an email message in your default mail program
Keywordsemail, mail, Outlook, Netscape
CategoriesOffice
 
Compose a mailto command as in (all on one line):

    mailto:me@nowhere.com?Subject=You must buy these books!
    &Body=Prototyping with Visual Basic%0D%0AVisual Basic G
    raphics Programming%0D%0AReady-to-Run Visual Basic Algo
    rithms%0D%0A

Then use the ShellExecute API function to "open" this command. It automatically launches your default email program, passing it the email parameters.

Be sure to replace special characters like carriage returns, line feeds, and ampersands with their hex values.

 
Public Sub SendMail(ByVal mail_to As String, Optional ByVal _
    mail_cc As String = "", Optional ByVal mail_bcc As _
    String = "", Optional ByVal mail_subject As String, _
    Optional ByVal mail_body As String = "")
    Dim strParameters As String
    Dim strCommand As String

    ' Compose the parameters.
    If Len(mail_cc) Then strParameters = strParameters & _
        "&CC=" & ReplaceSpecialCharacters(mail_cc)
    If Len(mail_bcc) Then strParameters = strParameters & _
        "&BCC=" & ReplaceSpecialCharacters(mail_bcc)
    If Len(mail_subject) Then strParameters = strParameters _
        & "&Subject=" & _
        ReplaceSpecialCharacters(mail_subject)
    If Len(mail_body) Then strParameters = strParameters & _
        "&Body=" & ReplaceSpecialCharacters(mail_body)

    ' If the parameters aren't blank,
    ' replace the initial & with ?.
    If Len(strParameters) Then Mid(strParameters, 1, 1) = _
        "?"

    ' Add the basic mailto command.
    strCommand = "mailto:" & mail_to & strParameters

    ' Send this to ShellExecute.
    ShellExecute Me.hwnd, "open", strCommand, _
        vbNullString, vbNullString, SW_SHOWNORMAL
End Sub

' Replace special characters with their hex codes.
Private Function ReplaceSpecialCharacters(ByVal txt As _
    String) As String
Dim i As Integer
Dim ch As String
Dim result As String

    For i = 1 To Len(txt)
        ch = Mid$(txt, i, 1)
        If (ch < " ") Or (ch > "~") Or (ch = "&") Then
            ' Replace with hex code.
            ch = Right$("00" & Hex(Asc(ch)), 2)
            result = result & "%" & ch
        Else
            ' Leave unchanged.
            result = result & ch
        End If
    Next i

    ReplaceSpecialCharacters = result
End Function
 
Note that this method may not work for very long messages, particularly those with more than 255 paragraphs (%0D%0A).

Thanks to Dien Ba Quan.

Thanks to WJK for fixing a bug that was truncating the command text.

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated