Click here to Skip to main content
6,305,776 members and growing! (17,009 online)
Email Password   helpLost your password?
General Programming » Internet / Network » Email     Intermediate

How to send a simple text email message

By Chad Z. Hower aka Kudzu

How to send a simple text email message.
C#, VB, Windows, .NET 1.1VS.NET2003, Dev
Posted:18 May 2004
Updated:14 Nov 2004
Views:122,368
Bookmarked:44 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
25 votes for this article.
Popularity: 5.22 Rating: 3.74 out of 5
2 votes, 8.0%
1
5 votes, 20.0%
2
1 vote, 4.0%
3
3 votes, 12.0%
4
14 votes, 56.0%
5

Sample Image - IndySMTP.gif

Introduction

This article will provide a very basic overview of how to send a plain text mail message with the open source Indy sockets library for .NET.

Constructing the Message

The following code is the basic structure for constructing a message:

C#
Indy.Sockets.Message LMsg = new Indy.Sockets.Message();
LMsg.From.Text = textFrom.Text.Trim();
LMsg.Recipients.Add().Text = textTo.Text.Trim();
LMsg.Subject = textSubject.Text.Trim();
LMsg.Body.Text = textMsg.Text;

Visual Basic

Dim LMsg As New Indy.Sockets.Message
LMsg.From.Text = textFrom.Text.Trim
LMsg.Recipients.Add.Text = textTo.Text.Trim
LMsg.Subject = textSubject.Text.Trim
LMsg.Body.Text = textMsg.Text

A call to the Clear method is necessary only if a single Message is being reused. Clear resets the message content and other fields to their default or empty states.

It is actually legal to send messages without From, Subject, and Body. However, such a message is not very useful and many servers will reject it either as faulty, or probable spam. Thus, these properties should be considered the minimum requirements for sending a message.

For more advanced messages, the Message class also has properties for CC, BCC, Attachments, HTML and more.

Sending the Message

Once a message has been constructed, it must be delivered to an SMTP server. This is done using the SMTP class. The following code is the basic form for sending a message:

C#

SMTP LSMTP = new SMTP();
LSMTP.Host = textSMTPServer.Text.Trim();
LSMTP.Connect();
try {
  LSMTP.Send(LMsg);
  Status("Completed");
}
finally {
  LSMTP.Disconnect();
}

Visual Basic

Dim LSMTP As New SMTP
LSMTP.Host = textSMTPServer.Text.Trim
LSMTP.Connect()
Try
  LSMTP.Send(LMsg)
  'Status("Completed")

Finally
  LSMTP.Disconnect()
End Try

The host must be set so that the SMTP class knows where to send the messages to. In the case of SMTP, the host can be thought of as the address of the local post office.

The Send method accepts one argument which specifies the Message class to send.

In this example, only one message is sent. However, the SMTP protocol allows for multiple messages, so it is not necessary to connect and disconnect if multiple messages are to be sent. To send multiple messages, simply make additional calls to the Send method while connected. Multiple Message instances can be used, or an existing one can be modified between calls to Send.

Send Mail Demo

A very basic demo of sending a simple mail message is available as SendMail.

In addition to the basics covered in this article, the demo also makes use of the OnStatus event. The OnStatus event is a core event of Indy but implemented differently by each protocol. OnStatus is fired at various times during calls to Connect, Send, and Disconnect. Each time, a text message is passed that explains what is occurring. OnStatus is designed to provide user interface updates, or logging. It's not designed for pragmatic interpretation of state. In the SendMail demo, the messages from OnStatus are displayed into a ListBox.

In this demo, the OnStatus event has been defined as follows:

C#

private void Status(string AMessage) {
  lboxStatus.Items.Add(AMessage);
  // Allow the listbox to repaint

  Application.DoEvents();
  Application.DoEvents();
  Application.DoEvents();
}

private void SMTPStatus(object aSender, Status aStatus, string aText) {
  Status(aText);
}

Visual Basic

Private Sub Status(ByVal aMessage As String)
  lboxStatus.Items.Add(aMessage)
  ' Allow the listbox to repaint

  Application.DoEvents()
  Application.DoEvents()
  Application.DoEvents()
End Sub

Private Sub SMTPStatus(ByVal aSender As Object, ByVal aStatus As Status, 
  ByVal aText As String)
  Status(aText)
End Sub

When the Send Mail button is pressed, the following code is executed to send the message:

C#

private void butnSendMail_Click(object sender, System.EventArgs e)  {
  butnSendMail.Enabled = false; 
  try {
    Indy.Sockets.Message LMsg = new Indy.Sockets.Message();
    LMsg.From.Text = textFrom.Text.Trim();
    LMsg.Recipients.Add().Text = textTo.Text.Trim();
    LMsg.Subject = textSubject.Text.Trim();
    LMsg.Body.Text = textMsg.Text;

    // Attachment example

    // new AttachmentFile(LMsg.MessageParts, @"c:\temp\Hydroponics.txt");


    SMTP LSMTP = new SMTP();
    LSMTP.OnStatus += new Indy.Sockets.TIdStatusEvent(SMTPStatus);
    LSMTP.Host = textSMTPServer.Text.Trim();
    LSMTP.Connect();
    try {
      LSMTP.Send(LMsg);
      Status("Completed");
    }
    finally {
      LSMTP.Disconnect();
    }
  }
  finally {
    butnSendMail.Enabled = true;
  }
}

Visual Basic

Private Sub butnSendMail_Click(ByVal sender As System.Object, 
  ByVal e As System.EventArgs) Handles butnSendMail.Click
  butnSendMail.Enabled = False
  Try
    Dim LMsg As New Indy.Sockets.Message
    LMsg.From.Text = textFrom.Text.Trim
    LMsg.Recipients.Add.Text = textTo.Text.Trim
    LMsg.Subject = textSubject.Text.Trim
    LMsg.Body.Text = textMsg.Text

    ' Attachment example

    ' Dim xAttachment As New AttachmentFile(

    '    LMsg.MessageParts, "c:\temp\Hydroponics.txt")


    Dim LSMTP As New SMTP
    AddHandler LSMTP.OnStatus, AddressOf SMTPStatus
    LSMTP.Host = textSMTPServer.Text.Trim
    LSMTP.Connect()
    Try
      LSMTP.Send(LMsg)
      'Status("Completed")

    Finally
      LSMTP.Disconnect()
    End Try
  Finally
    butnSendMail.Enabled = True
  End Try
End Sub

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Chad Z. Hower aka Kudzu


Member
Chad Z. Hower, a.k.a. Kudzu
"Programming is an art form that fights back"
Website: http://www.KudzuWorld.com
Blogspace: http://www.KudzuWorld.com/blogs/
Speaking Profile: http://www.woo-hoo.net/

Formerly the Regional Developer Adviser (DPE) for Microsoft MEA (Middle East and Africa), he was responsible for 85 countries spanning 4 continents and crossing 10 time zones. Now Chad is Microsoft MVP and a Microsoft Regional Director covering Europe, Middle East, Africa, and Asia and a professional speaker at popular developer conferences worldwide. Chad was once introduced as having "mastered more languages than a United Nations translator." Chad is the author of the book Indy in Depth and has contributed to several other books on network communications and general programming. Chad writes regularly for the Software Developer Network Magazine (Dutch), and occasionally for other magazines. Chad is an expatriate who travels extensively year round. Chad has lived in Canada, Cyprus, Jordan, Russia, Turkey, and the United States. In total Chad has visited more than 50 countries, visiting most of them many times.
Occupation: Software Developer (Senior)
Location: Cyprus Cyprus

Other popular Internet / Network articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 57 (Total in Forum: 57) (Refresh)FirstPrevNext
General[Message Deleted] Pinmemberit.ragester22:50 2 Apr '09  
QuestionPlease Help me Pinmemberpolash_p19:38 3 May '08  
AnswerRe: Please Help me PinmemberChad Z. Hower aka Kudzu7:00 4 May '08  
GeneralReply PinmemberAnjay19:18 11 Apr '08  
GeneralNice example - how about SMTPRelay? Pinmemberg18c22:17 12 Dec '07  
Generalhi Pinmemberjer marshall9:02 12 Dec '07  
Questionan i add PinmemberHesham yassin3:30 7 Jun '07  
GeneralPlz help me(mail msg) PinmemberAhmed El-Badry4:38 31 Jan '07  
GeneralError using a web service...... Pinmembercransaxbeth3:44 27 Dec '06  
GeneralAddress Rejected Error Message [modified] Pinmembercransaxbeth7:24 6 Dec '06  
GeneralRe: Address Rejected Error Message PinmemberChad Z. Hower aka Kudzu7:31 6 Dec '06  
GeneralRe: Address Rejected Error Message Pinmembercransaxbeth3:17 12 Dec '06  
QuestionCan't loop through messageParts PinmemberAndrej Kocevar4:35 11 Oct '06  
GeneralCannot build the solution Pinmembersanu201:51 4 Oct '06  
QuestionRe: Cannot build the solution PinmemberMatthijs ter Woord22:04 5 Oct '06  
GeneralSMTP server? PinmemberBryan Llanes19:55 17 Mar '06  
GeneralRe: SMTP server? PinmemberChad Z. Hower aka Kudzu0:37 19 Mar '06  
GeneralHow can I embedded an image in the Mail using VB.net? Pinmembergeorge bush 3315:39 15 Mar '06  
GeneralRe: How can I embedded an image in the Mail using VB.net? PinmemberChad Z. Hower aka Kudzu2:29 17 Mar '06  
GeneralHow to send accented characters in the subject line? PinmemberLairton Ballin3:44 3 Mar '06  
GeneralRe: How to send accented characters in the subject line? PinmemberChad Z. Hower aka Kudzu8:27 4 Mar '06  
GeneralCan't send mail!? Pinmemberfanaticus7:33 5 Oct '05  
GeneralSubject in email header Pinmemberpurse00121:51 7 Jul '05  
GeneralRe: Subject in email header PinmemberChad Z. Hower aka Kudzu4:38 8 Jul '05  
GeneralRe: Subject in email header Pinmemberpurse0014:59 8 Jul '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 14 Nov 2004
Editor: Nishant Sivakumar
Copyright 2004 by Chad Z. Hower aka Kudzu
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project