Important Note: Before you start with the example, I want you to know that you must have a valid “Hotmail” email id and password.
The SmtpClient() class of System.Net.Mail namespace along with NetWorkCreadential() class of System.Net namespace in .NET provides the necessary functions and properties using which we can easily send emails, add from and to email ids, add subject, body and attachments to your email, add CC (Carbon Copy) and BCC (Blind Carbon Copy), send images and files to your clients. In fact, you can create your own email service and more using the methods that the class provides.
However, you will also need a reliable SMTP Mail Server, which will accept the contents in the email and send it across to its recipient. Hotmail SMTP mail server is one the services that you can use and this example uses this service.
I’ll first create a small form, which will have few HTML elements. This form will accept user inputs such as, from and to email ids, a subject and the body of the email. Along with the markup, I have written few JavaScript codes for validation.
<!DOCTYPE html> <html> <head> <title>Send Email in Asp.Net using Hotmail SMTP Mail Server</title> <style> #container { width:450px; background:rgb(255, 251, 221); padding:10px; font:16px Georgia; font-style:italic; } input[type=text], textarea { /* STYLE ONLY INPUTBOX AND TEXTAREA. */ margin:8px; padding:8px 5px; background:#FFF; border-radius:10px;border:none; box-shadow:0 4px 6px -5px #333,inset 0 4px 6px -5px #333; font:16px Georgia; font-style:italic; letter-spacing:1.5px; width:300px; } input[type=submit] { /* STYLE THE BUTTON. */ cursor:pointer; width:100px; height:40px; } ul { padding:0; margin:0; } li { width:120px; display:inline-table; } </style> </head> <body> <form runat="server"> <div id="container"> <ul> <li>From Email</li> <li> <asp:TextBox ID="fromEmail" placeholder="From" runat="server"></asp:TextBox> </li> </ul> <ul> <li>To Email</li> <li> <asp:TextBox ID="toEmail" placeholder="To" runat="server"></asp:TextBox> </li> </ul> <ul> <li>Add a Subject</li> <li> <asp:TextBox ID="subject" placeholder="Subject" runat="server"></asp:TextBox> </li> </ul> <ul> <li style="vertical-align:top;padding-top:10px;">Email Body</li> <li> <textarea id="body" placeholder="Body" rows="8" cols="40" runat="server"></textarea> </li> </ul> <ul> <li> <asp:Button id="send" Text="Send Mail" OnClick="SendEmail" OnClientClick="return validate();" runat="server" /> </li> <li style="width:auto;"><label id="message" runat="server"></label></li> </ul> </div> </form> </body>
The script is very basic. I am just checking if the from and to fields have values. You can however write more script for validations like checking if the entered emails are valid emails, put word limits in the Body etc.
<script> function validate() { if (document.getElementById('fromEmail').value == '') { alert("Enter From Email ID"); document.getElementById('fromEmail').focus(); return false; } if (document.getElementById('toEmail').value == '') { alert("Enter Recipient's Email ID"); document.getElementById('toEmail').focus(); return false; } } </script> </html>
In the beginning of this article, I have mentioned two .NET namespaces such as, System.Net and System.Net.Mail, which provides the necessary functions to help us to create our email service. Therefore, in the code behind section you will add these namespaces in the beginning of the code.
using System; using System.Net; using System.Net.Mail; public partial class _Default : System.Web.UI.Page { protected void SendEmail(object sender, EventArgs e) { try { // ADD "FROM" AND "TO" ADDRESS, ALONG WITH THE SUBJECT AND BODY. MailMessage mail = new MailMessage( fromEmail.Text.Trim(), toEmail.Text.Trim(), subject.Text.Trim(), body.InnerHtml.Trim()); // DEFINE HOTMAIL SMTP MAIL SERVER ALONG WITH A PORT (587 IN THIS CASE) // USING SmtpClient() CLASS. SmtpClient client = new SmtpClient("smtp.live.com", 587); client.UseDefaultCredentials = true; // NETWORK CREADENTIALS. // YOUR HOTMAIL ID ALONG WITH THE PASSWORD. // NOTE: CHANGE THE STRING "your_hotmail_password" // WITH A VALID HOTMAIL PASSWORD. NetworkCredential credentials = new NetworkCredential(fromEmail.Text, "your_hotmail_password"); client.Credentials = credentials; client.EnableSsl = true; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Send(mail); // FINALLY, SEND THE MAIL. message.InnerText = "Your message has been sent."; message.Attributes.Add("style", "padding:2px 5px;background-color:#DFF0D8;color:#3C763D;"); } catch { message.InnerText = "Error. Unable to send mail."; message.Attributes.Add("style", "padding:2px 5px;color:red;"); } } }
Note: In the above code, you must change the value your_hotmail_password to your valid hotmail password. You can pass the value for the password using an Input box on the web page like the Email id’s and other values. However, I have hardcoded the password in this example. Always be careful with your passwords.
Option Explicit On Imports System.Net Imports System.Net.Mail Partial Class _Default Inherits System.Web.UI.Page Protected Sub SendEmail(ByVal sender As Object, ByVal e As EventArgs) Try ' ADD "FROM" AND "TO" ADDRESS, ALONG WITH THE SUBJECT AND BODY. Dim mail As New _ MailMessage(fromEmail.Text, _ toEmail.Text, Trim(subject.Text), Trim(body.InnerHtml)) ' DEFINE HOTMAIL SMTP MAIL SERVER ALONG WITH A PORT (587 IN THIS CASE) ' USING SmtpClient() CLASS. Dim client As New SmtpClient("smtp.live.com", 587) client.UseDefaultCredentials = True ' NETWORK CREADENTIALS. ' YOUR HOTMAIL ID ALONG WITH THE PASSWORD. ' NOTE: CHANGE THE STRING "your_hotmail_password" ' WITH A VALID HOTMAIL PASSWORD. Dim credentials As _ New NetworkCredential(fromEmail.Text, "your_hotmail_password") client.Credentials = credentials client.EnableSsl = True client.DeliveryMethod = SmtpDeliveryMethod.Network client.Send(mail) message.InnerText = "Your message has been sent." message.Attributes.Add("style", "padding:2px 5px;background-color:#DFF0D8;color:#3C763D;") Catch ex As Exception message.InnerText = "Error. Unable to send mail." message.Attributes.Add("style", "padding:2px 5px;color:red;") Finally End Try End Sub End Class
Well, you are ready with your email service.
Add HTML (Markup) TO EMAIL
You can however, some color and style to you emails. All most every modern email services today allow users to format there emails, accept few web mail services. You can highlight or bold certain texts on the body, create borders and add background colors to the body of the email etc. The classes that we have discussed above, provides features with which you can add Markups and CSS to the body.
For example, I wish to add a border around the Body of the email and set the background too. To do this I’ll add a <div> element and concatenate the Body text along with it. Just like this.
string sBody = ""; sBody = "<div style=border:solid 1px #CCC;background:rgb(255, 251, 221);padding:10px;>" + body.InnerHtml.Trim() + "</div>"; MailMessage mail = new MailMessage( fromEmail.Text.Trim(), toEmail.Text.Trim(), subject.Text.Trim(), sBody); mail.IsBodyHtml = true;
I have declared a string called sBody and assigned the HTML <div> element along with the contents of the Body. I have styled the element using CSS. I have replace body.InnerHTML with string variable sBody. Finally, I have set the isBodyHtml property to true. You have explicitly tell the class to show the Body content of email in HTML format.
Dim sBody As String = "" sBody = "<div style=border:solid 1px #CCC;background:rgb(255, 251, 221);padding:10px;>" & _ Trim(body.InnerHtml) & _ "</div>" Dim mail As New _ MailMessage(fromEmail.Text, _ toEmail.Text, Trim(subject.Text), sBody) mail.IsBodyHtml = True