Sending E-mail through Outlook using VB.net

April 30, 2008

 

This example shows how to add e-mail to Microsoft Outlook outbox using VB.Net .The most improtant point here to get this working is to add a reference to “Microsoft Outlook object library”, In case of Microsoft Outlook 2002, Add “Microsoft Outlook 9.0 object library” (Right click on the project -> Add References -> Select the COM tab -> Select “Microsoft Outlook 9.0 object library”.

 

Public Class Form1

Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click

If (txtTo.Text.Length > 0 And txtSubject.Text.Length > 0 And txtBody.Text.Length > 0) Then

Try

Dim ol As New Outlook.Application()
Dim ns As Outlook.NameSpace
Dim fdMail As Outlook.MAPIFolder

ns = ol.GetNamespace(“MAPI”)
ns.Logon(, , True, True)

‘creating a new MailItem object
Dim newMail As Outlook.MailItem

‘gets defaultfolder for my Outlook Outbox
fdMail = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderOutbox)

‘assign values to the newMail MailItem
newMail = fdMail.Items.Add(Outlook.OlItemType.olMailItem)
newMail.Subject = txtSubject.Text
newMail.Body = txtBody.Text
newMail.To = txtTo.Text
newMail.SaveSentMessageFolder = fdMail

newMail.Send()

Catch ex As Exception

Throw ex

End Try

End If

End Sub

End Class

 

Advertisements