Library tutorials & articles

SMTP Mailing Application

The Code

Next we design our mail application by placing textboxes for From, To, Copy, Blind Copy, Subject, Attachment, and the Message Body.  We then add corresponding labels for each of the textboxes. Also, we add a button for sending the message and a button to exit the application.  As an added feature, we placed a browse button next to the attachment so we can browse for attachments on our file system.  The browse button uses the OpenFileDialog component for navigating for an attachment (as seen at the bottom of the designer.)

 

Figure 5 - E-Mail Sender Design View

Below is the code used to send the email we construct in our form. The code is executed in the SendButton_Click Event Handler.   The method simply creates a new MailMessage instance and populates it with the text typed into the various fields by the user.  The MailMessage object is then sent using the SmtpMail.Send static function:

 

Listing 2 - Send Button Event Handler

private void SendButton_Click(object sender, System.EventArgs e)
{
 try
  {
// Construct a new mail message and fill it with information from the form

   MailMessage aMessage = new MailMessage();
   aMessage.From = FromTextBox.Text;
   aMessage.To = ToTextBox.Text;
   aMessage.Cc = CCTextBox.Text;
   aMessage.Bcc = BCCTextBox.Text;
   aMessage.Subject = SubjectTextBox.Text;
   aMessage.Body = MessageTextBox.Text;

// if an attachment file is indicated, create it and add it to the message
   if (AttachmentTextBox.Text.Length > 0)
      aMessage.Attachments.Add(new MailAttachment(AttachmentTextBox.Text, MailEncoding.Base64));

// Now send the message
    SmtpMail.Send(aMessage);

  // Indicate that the message has been sent
 MessageBox.Show("Message Sent to " + ToTextBox.Text);
}

catch(Exception ex)
 {
   MessageBox.Show(ex.Message.ToString());
 }

}

Below is the button event handler for populating the Attachment field through the Browse button.
It simply calls ShowDialog on the OpenFileDialog instance and if the result is ok it assigns the filename chosen by the user to the attachment field:

Listing 3 - Browse  Button Event Handler

private void BrowseButton_Click(object sender, System.EventArgs e)
{
  if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
  {
   AttachmentTextBox.Text = this.openFileDialog1.FileName;
  }
}

I suspect you'd be more likely to use Microsoft Outlook then this simple application, but you can utilize the code in this application to customize it to suit your specific needs.  For example, you might consider creating a database in access and writing C# and ADO.NET for accessing groups of people you'd like to send emails.  You could change this into a component and have it pop up when you need to send emails in your application.  In any case, this will get you started in your quest to send emails using .NET.

Comments

  1. 15 Jul 2009 at 02:55

    I found a very simple (and flexible) .NET Mail API. Check out EZ E-Mail .NET API @ http://www.get-a-code-monkey.com/MailProcessor.aspx

    Though, it may have limited functionality it's REALLY easy to use. They have example which make using it VERY simple.

  2. 07 Sep 2005 at 11:42

    Hi prazathin
    Not at all, good days

  3. 06 Sep 2005 at 09:11

    hi cicada
    Thank u

  4. 05 Sep 2005 at 13:41

    and aspx page html part <%@ Import Namespace="System.Web.Mail" %>
    ok?

  5. 05 Sep 2005 at 13:39

       <script runat="server">
    Sub MailGonder(Sender As Object, E As EventArgs)
     Dim NewMail As New MailMessage()
     NewMail.From = txtfrom.text
     NewMail.To = "mail@mail.com.tr"
     NewMail.Subject = txtsubject.text
     NewMail.Body = txtmessage.text


     SmtpMail.SmtpServer = "smtpservername"
     SmtpMail.Send(NewMail)


     Response.Write("Mail successfully")
     Response.End
    End Sub
           </script>
           <script runat="server">
    Sub clean(Sender As Object, E As EventArgs)
     txtFrom.text=""
     txtSubject.text=""
     txtMessage.text=""
    End Sub
           
           </script>

  6. 05 Sep 2005 at 11:42
    Sir,
     I was trying to send mail through SMTP in vb.net..I was not able to import system.web.mail namespace.Do i have to install anything for this..
  7. 04 Aug 2005 at 21:00

    hi, I'm an ASP.Net developer, i need to create a table in my sqlserver dyanmically by sending the values from a textbox from my asp application, can u help me to get going
    ,u can contact me  in chezhian_in05@rediffmail.com.

  8. 08 Jul 2005 at 17:36

    Hi guys,


    I am using email in my app and using attchments as well. Does anybody knows how to load the icon of the attached document instead of whole path in a text box and place it in a picture box ?


    Thanks
    Mehrdad

  9. 08 Jul 2005 at 17:34

    Hi guys,


    I am using email in my app and using attchments as well. Does anybody knows how to load the icon of the attached document instead of whole path in a text box and place it in a picture box ?


    Thanks
    Mehrdad

  10. 28 Jun 2005 at 05:24
    Hi,

             Thanks. Its working.
                                                                                      Regards,
                                                                                      PremLatha.
  11. 27 Jun 2005 at 16:40
    Don't forget that framework should be installed on the target computer. That is the base for any .net application.

    Mehrdad
  12. 27 Jun 2005 at 16:36
    Hi everyone. IF you use the .net email on a computer that is a server and has SMTP running on it, then you are fine. This is the only that .net email works. Also make sure that you initialize all the entries with = "", otherwise it crashes. If you want to use it on a computer that does no act as a server, simply search for FreeSMTP and install it on your system and instead of using .net email, use the FreeSMTP control.

    It works.
    Mehrdad

  13. 27 Jun 2005 at 13:18
    Install IIS 5.1 on that machine, if possible install Microsoft exchange server also. No need to install .net
  14. 27 Jun 2005 at 10:30
    I try to send an email in C#, it is working in .net installed system. But not working in system where .net is not installed. the exception says (Could not access 'CDO.Message' object ) . Please help me to clear this.

    Thanks & Regards,

    PremLatha.
  15. 17 Jun 2005 at 07:01

    System.Web.Mail.SmtpMail.SmtpServer = MailServer; // SMTP Server IP
    MailMessage mailMessage = new MailMessage();
    //Set the SMTP Authentication details


    mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpa
    uthenticate", "1");    //basic authentication


    mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendu
    sername", MailUserID ); //set your username here


    mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendp
    assword", MailPassword );    //set your password here


    System.Web.Mail.SmtpMail.Send(mailMessage);


    Nitin Chaudhary
    Email: nitin_chaudhary@yahoo.com

  16. 13 May 2005 at 10:00
    please can u let me know how to add filedialog1 component
  17. 05 May 2005 at 18:08

    I know this makes little to no sense, but I too had the exact code working on a .Net app and it too studdenly stopped working.


    One simple line fixed it, reasons unknown, just try this....


    mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout", 60)


    The default value for smtp connection timeout is 30 seconds. I just beefed up that part.  I guess 30 seconds wasn't enough for all SMTP connection (incl. name resolution, user authentication, etc. ).


    Hope this helps,
    Brian
    brian.pressman@iko.com

  18. 17 Sep 2004 at 05:01

    Hi Guys, can u help with some web sites that i can visit to learn more about .Net platform.


    Cheers
    TK

  19. 29 Aug 2004 at 20:18

    Hi guys,


    I also have the same problem and REALLY don't know how to come over it. You may have found the solution for it yet I just got it. Could you guys help me too?


    YOu may also contact me directly : mehrdada@shaw.ca
    Thanks
    Mehrdad

  20. 12 Jan 2004 at 03:39
    Have you found any solution to this problem yet ? I am experiencing the same issue.
  21. 29 Dec 2003 at 14:08

    This article is great!  I'm very impressed as a .NET newbie.


    I send 3 messages to myself at interval of 5 minutes.  all three of them arrived about 45 minutes later.


    How does the method work?  Does it queue up a certain number of message & send them at same time.  Is there a way to send the mail messages instantly?


    puzzled!



  22. 29 Dec 2003 at 02:36

    Hi,


    I have tried to send the email similar to what you have done, with the exception of specifying the SmtpMail.SmtpServer.


    But when I try to send an email there is an exception that says (Could not create 'CDO.Message' object ) . Can you help me out with this?


    thank you.


    Swetha

  23. 19 Aug 2003 at 03:44

    Hello;


    thank you for your work.
    but when i tried to send an email there was an exciption that say (could not acess 'CDO.Message' object )
    so what can i do??


    thank you.


    Younis Alomoush

  24. 16 May 2003 at 03:34

    Because, I am a Vietnanese, so my English quite poor.
    I think that, when a source to send a message, we need a host mail to send, but in this source code, I can't see  about any host.
    I tried to send a message, but I can't receive a message which I send.
    Thank a lot.
    Nguyet Anh.

  25. 07 May 2003 at 09:52

    If SmtpServer property is not set, the name of the local SMTP server is used. Set SmtpServer property of the SmtpMail class (Assign IP address) to make it work over the internet.

  26. 19 Feb 2003 at 05:37
    I think your desktop should also
    have the CDO  dlls installed (registered).
    If you don't want this route,  try to
    create your own mail compnent.  I refer
    you to search google for 'smtp mail component in c#'.

  27. 04 Oct 2002 at 18:36

    This code works great on my development machine.


    MailMessage myMail = new MailMessage();
    myMail.From = "me@yahoo.com";
    myMail.To = "hardware@yahoo.com";
    myMail.Subject = EmpCurrent.WholeName + " Has sent Purchase
    Requisition #" + lblReqNumber.Text + " to you for your review.";
    myMail.Priority = MailPriority.Normal; myMail.BodyFormat = MailFormat.Html;
    myMail.Body = "Please review and reject or approve as soon as possible.";
    SmtpMail.Send(myMail);


    But when I install it on a desktop, it gives the following message every time:
    Any Ideas?


    Here is the error message:



    *** Exception Text ***
    System.Web.HttpException: Could not create 'CDONTS.NewMail' object.
      at System.Web.Mail.LateBoundAccessHelper.get_LateBoundType()
      at System.Web.Mail.CdoNtsHelper.Send(MailMessage message)
      at System.Web.Mail.SmtpMail.Send(MailMessage message)
      at PerfectReqs.PerfectReq.MenuActionSubmitOnClick(Object sender,
    EventArgs e)
      at System.Windows.Forms.MenuItem.OnClick(EventArgs e)
      at System.Windows.Forms.MenuItemData.Execute()
      at System.Windows.Forms.Command.Invoke()
      at System.Windows.Forms.Control.WmCommand(Message& m)
      at System.Windows.Forms.Control.WndProc(Message& m)
      at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
      at System.Windows.Forms.ContainerControl.WndProc(Message& m)
      at System.Windows.Forms.Form.WndProc(Message& m)
      at System.Windows.Forms.ControlNativeWindow.OnMessage(Message& m)
      at System.Windows.Forms.ControlNativeWindow.WndProc(Message& m)
      at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg,
    IntPtr wparam, IntPtr lparam)

  28. 01 Jan 1999 at 00:00

    This thread is for discussions of SMTP Mailing Application.

Leave a comment

Sign in or Join us (it's free).

Mike Gold Mike Gold is President of Microgold Software Inc. and Creator of WithClass 2000 a UML Design Tool for C#. In the last few years Mike has consulted for companies such as Merrill Lynch and Chase Manh...

Related discussion

Related podcasts

  • Object-Oriented Programming in Ruby

    In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...

Want to stay in touch with what's going on? Follow us on twitter!