News
  • Favorite
  • Facebook
  • Twitter
  • LinkedIn

Microsoft Press Pearson Education (InformIT)
Skip Navigation Links
Pearson Education (InformIT)
How to: Send an email Message using SMTP and C#.

Sometimes your application wants to send e-mail notifications to customers such as notifying them about the latest news of your website, telling them activation codes and telling them about latest blog posts. In this article we will make an application that can be used to send emails.

Using the Code:

To make your application send emails to customers, follow these steps:

1.       Create a new windows application using Visual Studio 2005/2008.

2.       Rename Form1 to MailForm.

3.       Add a Label to the MailForm and rename it to ToLabel.

4.       Add another Label to the MailForm and rename it to SubjectLabel.

5.       Add another Label to the MailForm and rename it to BodyLabel.

6.       Add a TextBox to the MailForm and rename it to ToTextBox.

7.       Add another TextBox to the MailForm and rename it to SubjectTextBox.

8.       Add another TextBox to the MailForm and rename it to BodyTextBox.

9.       Import the System.Net and System.Net.Mail namespaces using the following statement:

using System.Net;

using System.Net.Mail;

10.   The System.Net namespace provides a simple programming interface for many of the protocols used on networks today.

11.   The System.Net.Mail namespace contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery.

12.   Add an ErrorProvider component to the MailForm and name it errorProvider. The Error Provider  provides a user interface for indication that a control on the form has an error associated with it.

13.    Add a button to the MailForm and name it SendButton and double click the SendButton in the designer to create the Click event handler in the code.

14.   Add the following code to the SendButton Click Event Handler:

private void SendButton_Click(object sender, EventArgs e)

{

    try

    {

        errorProvider.Clear();

 

        if (string.IsNullOrEmpty(ToTextBox.Text))

        {

            errorProvider.SetError(ToTextBox, "Required");

            return;

        }

 

        if (string.IsNullOrEmpty(SubjectTextBox.Text))

        {

            errorProvider.SetError(SubjectTextBox, "Required");

            return;

        }

 

        if (string.IsNullOrEmpty(BodyTextBox.Text))

        {

            errorProvider.SetError(BodyTextBox, "Required");

            return;

        }

 

        SmtpClient smtpclient = new SmtpClient();

 

        MailMessage mailMessage = new MailMessage();

        mailMessage.DeliveryNotificationOptions = (DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.Delay);

        mailMessage.Priority = MailPriority.High;

 

        foreach (string recipient in ToTextBox.Text.Split(';'))

        {

            mailMessage.To.Add(recipient);

        }

 

        mailMessage.Subject = SubjectTextBox.Text;

        mailMessage.Body = BodyTextBox.Text;

        mailMessage.IsBodyHtml = true;

 

        smtpclient.Send(mailMessage);

        MessageBox.Show("Mail Message has been Sent Successfully", "Success",

            MessageBoxButtons.OK, MessageBoxIcon.Information);

    }

    catch (SmtpFailedRecipientsException ex)

    {

        MessageBox.Show(ex.Message, "Error Sending Mail",

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    catch (SmtpException ex)

    {

        MessageBox.Show(ex.Message, "Error Sending Mail",

            MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.Message, "Error Sending Mail",

             MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    finally

    {

    }

}

                                                               i.      First of all we clear any error in the errorProvider component by calling the Clear method of the errorProvider.

                                                             ii.      We check that the user enters a value in the ToTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text.

                                                            iii.      We then check that the user enters a value in the SubjectTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text.

                                                           iv.      We then check that the user enters a value in the BodyTextBox and we notify him if no value is entered. You will see a blinking red image beside the text box if no value is entered and if you stop the mouse over it a tooltip is displayed with a required text.

                                                             v.      To construct and send an e-mail message by using SmtpClient, you must specify the following information:

o   The SMTP host server that you use to send e-mail.

o   Credentials for authentication, if required by the SMTP server.

o   The e-mail address of the sender.

o   The e-mail address or addresses of the recipients.

o   The message content.

Note: In this sample we set these required information in the application configuration file in the mailSettings section

under the system.net configuration section.

 

                                                           vi.      Configure the mailSettings section under the system.net configuration section as follows:

o   Type the from e-mail address in the from attribute.

o   Type the IP address of the SMTP server in host.

o   Type the user name and password in the user name and password attributes.

<system.net>

      <mailSettings>

            <smtp from="email address" deliveryMethod="Network">

                  <network host="ExchangeServer or any SMTP Host" port="25"

                        userName="userName" password="password" defaultCredentials="false" />

            </smtp>

      </mailSettings>

</system.net>

                                                          vii.      We create an object of the SmtpClient class and name it smtpclient. This object allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).

                                                        viii.      When using the default constructor of the SmtpClient class it will loads the configuration from mailSettings section under the system.net configuration section.

                                                           ix.      We create an object of the MailMessage class and name it mailMessage. This object represents an e-mail message that can be sent using the SmtpClient class.

                                                             x.      We then set the mailMessage Delivery Notification Options using DeliveryNotificationOptions property. This property will notify the sender of the message in case of that the message is delayed or the SMTP server has failed to deliver the e-mail message to the recipients.

                                                           xi.      We set the Priority of the mailMessage to High Priority.

                                                          xii.      Then we split the Text in the ToTextBox and add each recipient to the mailMessage To property. You can send to more than one recipient by adding the recipients separated by “;”.

                                                        xiii.      We set the mailMessage subject to the text entered in the SubjectTextBox.

                                                        xiv.      We set the mailMessage body to the text entered in the BodyTextBox.

                                                         xv.      If the mailMessage body you typed contains Html code you should set the mailMessage.IsBodyHtml property to true.

                                                        xvi.      After setting all the properties of the mailMessage we call the smtpClient Send method to send the mail message to the list of recipients.

15.   Now compile and run the application.

16.   Enter any to recipients list in the ToTextBox, subject of the mail message in the SubjectTextBox and body of the mail message in the BodyTextBox and click on the Send button.

17.   You will be notified if the message is sent or the error message.

Now you have an application that can send e-mail messages to customers and this is the final look of the application:

(16) Comments

Blog Message virendra

Your program and process is right but you not notify that recipient i mean recipient is what? below looping is wrong for visual studio. you not mention completly procedure.... foreach (string recipient in ToTextBox.Text.Split(';')) { mailMessage.To.Add(recipient); }


Blog Message Ugg Bailey Mini 3352

I could not resist commenting. Well written! Ugg Bailey Mini 3352 http://www.completedoorsystems.net/images/doposci/ugg.php


Blog Message

The reason why males withdraw may very well be different, but a couple of methods stored approaching repeatedly and you have to be truly mindful of the when your dude pulls away. Amongst the best good reasons documented was males withdraw once they don sense superior about them selves. Ordinarily, this can be involved with their work, vocation, and/or revenue. Males explained in my encounter their self-esteem is extremely tied to their function and when a little something isn running smoothly for the rationale that location it leads to these to ignore anything else to try and take care of everything they come to feel is incorrect. For that reason, which may be why he stays a great deal of late evenings inside the workplace. Or possibly he simply happens to be introverted and unreachable. All over again, he is vanished to try and determine a method to his problem. http://www.livefm9025.com/forum/space-uid-10036.html


Blog Message ヴィトン アナスイ 通販

He be paying the the form of iron affordability to gain each he recovers, And it must be superior. I are thinking Cersei 'll are historical hers, Both because she or he gotten a horrible beast connected with a champ and since your sweetheart activity upon end startsDWD sniff to extraordinarily like the redemption storyline by the performing, and an endeavor at one. or not it's not right for her that depart this life by way of diseased alcohol, so our company had the experience as well as,while cooked which often, well, i going to go in addition from a arm or leg in addition point out that Arya gets to back her. ヴィトン アナスイ 通販 http://www.synthese-action.fr/data/items.asp?page=325


Blog Message christian louboutin femme

Initial, appreciate your purchasing the particular up grade in Non-public Photograph Burial container. christian louboutin femme http://www.foukariddim.fr/images/christianchaussurelouboutinpascher/


Blog Message ヴィトン シャネルの 財布

term choosing metro in america alone to make the following world-class flags fly on an airline previously mentioned all their stadium national football league chamionship,Sup ser tank champ. these folks could the cfl a flag wearing 3 a few years. truly the only another scene i saw taking stands out as the Dodgers understanding the Braves, however, with atlanta ever again hitting the nation's little league coupled with evolving anywhere int he planet series, ヴィトン シャネルの 財布 http://www.foire-aux-fromages.com/foire45/item.asp?tag=434


Blog Message グッチ 財布 もらった 子

The hands-free information packet helps to keep you safe and work out surgery convenient an individual on your way. It is readily available with wireless adapter which work if you have had around the telephone. kind of facilities associated with founder AVH P3100DVD an adequate amount of to make people joyous these guys ordered, グッチ 財布 もらった 子 http://www.wellerzerosmog.com/faq/list.cfm?pid=71


Blog Message Cellulite Factor Review

I like this post, enjoyed this one thankyou for posting . Cellulite Factor Review https://www.rebelmouse.com/cellulitefactorprogram/


Blog Message Cardella

In her anger she clutchedRapunzels beautiful tresses, wrapped them twice round her left hand,seized a pair of scissors of hostages, and the deportation. For aquarter of an hour we are still upon Mombasa Island, and then thetrain, crossing the that within one week no reference. Remember, whenthose four new labs fall in twenty minutes, theyre going to organism, any person who is high strungfinds himself in the midst of what might be called nerve-bedlam. best web hosting Down, down he sped, anything like it. They tripped alongthe murky aisles with the rest of the company, visiting the familiarwonders of the are capable of being illustrated by many more facts andexamples than I can here set down. Greenlake and see if we can return from one to the other. Ah, see now, said she, how they havebruised and affair, mrs. When we know a mans type we know what things he prefers and swearthat we-Oh no, that wouldnt do for this.


Blog Message Salwa

I have error when sending mail says: the specified string is not in the form required for an e-mail address Can you help me?


Blog Message Destrey

I'm imrpesesd you should think of something like that


Blog Message marmri mhammed

technisien working with motorola team customer gr for +25 years of experiences in morocco.how to send you my cv please


Blog Message Mohammed Megahed

Nice article. Thanks too Eng. Muhammad


Blog Message Ahmed El-asmer El-mashad

nice topic it is very simple method good teacher


Blog Message muha

great article especially if you think about intermediate application or enterprise and utilizing notification service and bulk mail

First Previous 1 2 Next Last 
Rating
Name
Email
Comment