Send an E-Mail through Exchange Server from .NET
In order to send an email from Exchange server , I have been using the MS Outlook type library in VB6 to dynamically create an Outlook mail item and set the appropriate properties and send it. Current
May 19, 2004
In order to send an email from Exchange server , I have been using the MS Outlook type library in VB6 to dynamically create an Outlook mail item and set the appropriate properties and send it. Currently, I had a requirement which required me to send a corporate email through the Exchange Server.
The easiest way I found was to create a COM in VB6 which does the necessary work , secondly create a .NET wrapper for the VB6 component (ActiveX DLL) and for this article creating a small console application which calls the .NET wrapper.
Here is the code for the VB6 component.
Public Function OutlookMail(ByVal EmailId As String, ByVal Sub As String,ByVal Body as String) As String Dim oApp As Outlook.Application Dim oMail As Outlook.MailItem On Error GoTo ErrHandler Set oApp = New Outlook.Application Set oMail = oApp.CreateItem(olMailItem) oMail.To = EmailId oMail.Subject = Sub oMail.Body = Body oMail.Send Set oMail = Nothing Set oApp = Nothing MailPwd = "True" Exit Function ErrHandler: MailPwd = Err.Description End Function |
Add MS Outlook Library in references for this project. Compiling it , i get SendMail.dll.
Step 2 requires us to create a .NET wrapper which is called the Runtime Callable Wrapper (RCW) for the COM
component. This is accomplished by using the tlbimp.exe utility. The command is given below.
tlbimp sendMail.dll /out:c:myAppbinsendMail.dll
This creates a RCW for our COM component and saves it in the appropriate directory.
Step 3 is creating a console application for using the wrapper.I have used C#for the same.
Here is the code for the console application (console.cs)
using System; using mBanking ; class Test { public static void Main() { SendMail.Mail oSM = new SendMail.Mail(); System.Console.WriteLine("created"); try { string status = oSM.OutLookMail("[email protected]", "Test", "Hi, This is a Test"); if (status == "True") { System.Console.WriteLine("sent mail"); } else { System.Console.WriteLine(status); } } catch(Exception ex) { Console.WriteLine(ex.Message); } } } |
Compile the above code using the following command
csc /r:sendMail.dll console.cs
You can run the console.exe from command prompt to send the mail. Happy Coding !!!!
Read more about:
MicrosoftAbout the Author
You May Also Like