SENDING MAIL USING OUTLOOK IN VB.NET
One of my clients required a desk top application that maintains contacts in a database and sends emails to the contacts in the database. They have not provided the credentials and the details of mail server. So I created an application that uses outlook for sending mails by using the credentials preconfigured by the outlook account. This application can send email for multiple email accounts and with or without attachments.
· Sending mails to multiple email accounts at a time.
· Using configured outlook credentials.
· No need of configuring credentials every time.
· Sending mails with attachments.
Create new project and add references as follows. These files can be downloaded or can be achieved by the sample project which is attached with this article.
Let’s go to code part. Import the following libraries apart from default
Here we need to create instances for outlook application; namespace and the namespace should be configured with the instance of the outlook application. We need to configure the outbox i.e., the place where the sent mail will be saved in our mail folder. Then we need to add credentials for this account. Here we are not going to give any credentials because we need to obtain the credentials from the native outlook application using the code. The code for this process will be as follows.
Dim ol As New Outlook.Application()
Dim ns As Outlook.NameSpace
Dim fdMail As Outlook.MAPIFolder
ns = ol.GetNamespace("MAPI")
ns.Logon(, , True, True)
Now create a new outlook mail item and necessary fields like subject, body, destination folder for saving the message and the priority as follows,
Dim newMail As Outlook.MailItem
'gets defaultfolder for my Outlook Outbox
fdMail = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderOutbox)
'assing values to the new mail mailitem
newMail = fdMail.Items.Add(Outlook.OlItemType.olMailItem)
.Subject = txtSubject.Text
.Body = txtBody.Text
.SaveSentMessageFolder = fdMail
.Importance = Outlook.OlImportance.olImportanceHigh
Add Mail recipients to the mail item. You can add more than one recipient for sending the same mail to many recipients as follows.
For Each checkedindex In chklstboxEmails.CheckedItems
Add attachments as follows.
If (lblAttachmentFile.Text <> "No File Selected..") Then
Dim attachments As Outlook.Attachments = newMail.Attachments
Dim attachment As Outlook.Attachment
Dim sourcefile As String = lblAttachmentFile.Text
Dim displaytext As String = sourcefile.Substring(sourcefile.LastIndexOf("\") + 1)
Dim bodylength As String = newMail.Body.Length
attachment = attachments.Add(sourcefile, , bodylength + 1, displaytext)
After that you can send the mail using the send() method.
This is how we can send mails by using the outlook and outlook preconfigured credentials.
Your comments are valuable for me,Thanking you,