Introduction
Sending an email is very easy in C#, this article provides an example of how to send email in WPF. This article uses the SmtpClient class, MailMessage class and MailAddress class. In the constructor of the MailAddress class an email address and display name of the user is provided. The MailMessage constructor take two objects of the MailAddress class as the sender address and receiver address. SmtpClient sends and receives email. This article uses the Send method of the SmptClient class.
There are only four steps to send a simple email using the SmtpClient class.
Procedure
The following is the procedure to send a simple email:
- Specify the name of the SMTP Server
- Provide specific credentials to SmptServer
- Create the e-mail message.
- Send the e-mail message
![mail.jpg]()
Use the following controls in your WPF application. They will help you to send the message.
![SendMail.jpg]()
Ensure your have imported the namespaces "System.Net.Mail" and "System.Net". If not imported in the Solution Explorer of Visual Studio then right-click on your project and click on "Add Reference".
![SendMail1.bmp]()
The Add reference window will open, select "System.Net" than click the "OK" Button.
![2.jpg]()
Import the following two namespaces:
Create an object of the SmtpClient class, set the server host name to the Host property and set the server port to the port property of Smtpclient. The following code uses 81 as the port as an example.
Create an object of the NetworkCredential class to provide the credential details to the object of SmtpClient class. Set the user name and password of the NetworkCredential class and provide this object to SmtpClient Credential.
Create two objects of the MailAddress class for the Sender address and Receiver address. MailAddress as a minimum takes two parameters to create an address, one is the email address and the other their display name, this the following sample provides two parameters, the sender address and their display name, again the same thing as done for the receiver address.
Now create an object of the MailMessage class. Here two parameters are provided to the constructor of the MailMessage class, one is the sender's address and the second is the receiver's address. The Subject text from the txtSubject control is passed to to Subject and mail's content is passed to Body of the MailMessage class as in the following:
Finally the send method of the SmtpClinet class is called to send the email.
Full code