Monday, February 16, 2009

How to make an simple SMTP client

There is nothing to it. MSDN example does it all. All you need is to call System.Net library. Here is a simple implementation:

Imports System
Imports System.Net
Imports System.Net.Mail
Imports System.Net.Mime
Imports System.Threading
Imports System.ComponentModel

Module SimpleAsynchronousExample

  Dim mailSent As Boolean = False

  Private Sub SendCompletedCallback(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)

    'Get the unique identifier for this asynchronous operation.
    Dim token As String = CType(e.UserState, String)

    If (e.Cancelled) Then
      Console.WriteLine("[{0}] Send canceled.", token)
      If (e.Error IsNot Nothing) Then
        Console.WriteLine("[{0}] {1}", token, e.Error.ToString())
        Console.WriteLine("Message sent.")
      End If
      mailSent = True
    End If
  End Sub

  Sub Main(ByVal args As String())
    'Command line argument must the the SMTP host.
    Dim client As SmtpClient = New SmtpClient("hostname")
    '' Specify the e-mail sender.
    '' Create a mailing address that includes a UTF8 character
    '' in the display name.
    Dim from As MailAddress = New MailAddress("", "Some" + " One", System.Text.Encoding.UTF8)
    ' Set destinations for the e-mail message.
    Dim toAddress As MailAddress = New MailAddress("")
    '' Specify the message content.
    Dim message As MailMessage = New MailMessage(from, toAddress)
    message.Body = "This is a test e-mail message sent by an application. "
    ''Include some non-ASCII characters in body and subject.
    message.Body += Environment.NewLine + "This is a mail"
    message.BodyEncoding = System.Text.Encoding.UTF8
    message.Subject = "test message 1" + "test message"
    message.SubjectEncoding = System.Text.Encoding.UTF8
    ' Set the method that is called back when the send operation ends.
    AddHandler client.SendCompleted, AddressOf SendCompletedCallback
    ' The userState can be any object that allows your callback 
    ' method to identify this send operation.
    'For this example, the userToken is a string constant.
    Dim userState As String = "test message1"
    client.SendAsync(message, "this is me")
    Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.")
    Dim answer As String = Console.ReadLine()
    '' If the user canceled the send, and mail hasn't been sent yet,
    '' then cancel the pending operation.
    If (answer.StartsWith("c") AndAlso mailSent <> False) Then
    End If
    ''Clean up.
  End Sub

End Module

In order for example to work hostname of a SMTP server must be entered. Also make sure to have relay rules set. If you want no rule to apply set:


Mutuelle sante said...

Thank you it has been a great guide, now to make an simple smtp client is without a doubt easy utilizing your tips. Thank you

Damijan said...

Glad I could help :)