0

Email from code

Whilst trying to come up with ways to make life easier at work I noticed that automating an email to appear with a subject, addressee and body pre-populated could save a lot of time in some circumstances – genius.

Trying to find a good way to do this wasn’t quite so easy however. Piecing together code from various forums and webpages I’ve come up with the below multi-purpose sub which can be called from anywhere within the program.
Note:
As this is a sub that I use regularly I will likely update this page with refinements as I make them. If you’ve any refinements on anything that I’ve posted feel free to get in touch and let me know.

Code

First put the following statement at the top of your module (you don’t have to do this in a module that’s just force of habit for me):

Imports Microsoft.Office.Interop

and add the Microsoft.Office.Interop.Outlook reference (project>add reference) and declare the below two variables:

Public moApp As Outlook.Application
Public mbKillMe As Boolean = True

These first two subs deal with checking whether outlook is open and whether to close it when the application closes. Reference the first when your application opens and reference the second when your application closes:

Public Sub SetOutlookInfo
    Try
        moApp = CType(GetObject(, "Outlook.Application"), Outlook.Application)
        mbKillMe = False
    Catch ex As Exception
        Try
            If moApp Is Nothing Then
                moApp = New Outlook.Application
                mbKillMe = True
            End If
        Catch ex As Exception
            MessageBox.Show("Outlook is not installed or available.",
                            "Limited Functionality", MessageBoxButtons.OK)
        End Try
    End Try
End Sub
 
Public Sub CloseOutlook
    If mbKillMe = True Then
        If Not moApp Is Nothing Then
            moApp.Quit()
            moApp = Nothing
        End If
    End If
End Sub

The sub that is called when you want to send an email allows you to customise each email individually with by passing in strings for the addressee, subject and body with an option to enter a string to CC.

Public Sub SendMail(ByVal _Addressee As String, ByVal _Subject As String,
                    ByVal _Body As String, Optional ByVal _CC As String = "")
    Dim oEmail As Outlook.MailItem
    Form1.Cursor = Cursors.WaitCursor
    Try
        oEmail = DirectCast(moApp.CreateItem(Outlook.OlItemType.olMailItem), Outlook.MailItem)
        With oEmail
            .To = _Addressee
            '.CC = "ruff@example.com"
            If _CC <> "" Then .CC = _CC
            .Subject = _Subject
            .BodyFormat = Outlook.OlBodyFormat.olFormatHTML
            If _Body <> "" Then .Body = _Body
            .Importance = Outlook.OlImportance.olImportanceNormal
            '.ReadReceiptRequested = True
            '.Attachments.Add("C:\Cat.bmp", Outlook.OlAttachmentType.olByValue)
            'Resolving recipients (below) triggers a security warning 
            'that users need to click through
            '.Recipients.ResolveAll()
            '.Save()
            .Display() 'Show the email message and allow for editing before sending
            '.Send() 'You can automatically send the email without displaying it.
        End With
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
    Form1.Cursor = Cursors.Default
End Sub

Feel free to play around with the options that I’ve commented out (the code above was copied and pasted out of a project that I’m playing with at the moment) and if you’ve any improvements just let me know and I’ll post it – and likely use it in my projects as well.

JBaker

Joi is an IT Development Analyst working in London and a consummate technophile. Whilst he isn't coding he can be found reacquainting himself with his guitars, spinning poi, looking for climbing walls or chasing the latest shiny thing to cross his field of vision.

Leave a Reply

Your email address will not be published. Required fields are marked *