Sunday, September 13, 2009

Send Mail in ASP.net 2.0 using SMTP Client and Mail Message with GMail

Send Mail Using SMTPClient and MailMessage in ASP

Send Mail Using SMTPClient and MailMessage in ASP.net 2.0 with GMail


Introduction

Sending Mail is become essential to web development and many sites. They used to send the reminders, the promotions to the subscribers and so forth. Email serves as the asynchronous notification and information distribution system.

Fortunately, ASP.net makes sending email very ease and powerful. Now the developer can utilize and develop powerful mailing system with very few lines of code. The .Net Framework provides the very rich sets of object which is used to send mail. System.Net.Mail namespace has all the class (objects) which one can use to send mails.


Exploring the Classes in the System.Net.Mail Namespace

There are 16 different classes in the System.Net.Mail namespace, all related to send email to a specified Simple Mail Transfer Protocol (SMTP) server for delivery. The two core classes in this namespace are:

  • MailMessage - represents an email message; has properties like From, To, Subject, Body, and so on.
  • SmtpClient - sends a specified Mail Message instance to a specified SMTP server.


Numbers of Steps performed to send mail using ASP.net 2.0 are

  1. Create the MailMessage Object with all the information has mentioned above
  2. Create the SmtpClient Object to send the Message created using the MailMessage Object.
  3. Specify the SMTP Host (server) name and its port to send mail from the specified mail id.
  4. You can use the GMail Smtp server to send mail if you don’t have one.
  5. You can send the attachment with the mails which you can specified to Mail Message properties.


Configure SMTP Server Configuration in Web.Config File


Add below code in config file and replace the properties with actual values

Configuration >
  
  system.net>
    mailSettings>
      
        
             host="serverName" 
             port="portNumber"
             userName="username"
             password="password" />
      
    
  
 
  
    ...
  


You can configure the SMTP properties in code behind too depends how you want to use.

Send Mail from Mailing Page

Default.aspx

<table bordercolor="#339933" cellspacing="0" cellpadding="4" width="55%" align="center" border="1">
<tr>
<td>
<table cellpadding="4" width="70%" align="center" border="0"> <tr bgcolor="#339933"> 
    <td align="center" colspan="2" style="background-color: #999999"><span id="lblHeader" style="font-weight:bold;">Gmail Account Details for Sending Mailsspan>td> tr>
<tr>
<td valign="middle" align="right" width="40%">Username:td> <td
valign="middle" width="60%"> <input name="txtUserName" type="text" id="txtUserName" style="font-family:Verdana;font-size:X-Small;width:350px;" />
td>
tr>
<tr>
<td valign="middle" align="right" width="40%">Passwordtd> <td
valign="middle" width="60%"> <input name="txtPassword" type="password" id="txtPassword" style="font-family:Verdana;font-size:X-Small;width:350px;" />
td>
tr>
<tr bgcolor="#339933"> <td align="center" colspan="2" 
        style="background-color: #999999"><span id="Label1" style="font-weight:bold;">SMTP
Mail with Attachmentspan>td>
tr>
<tr>
<td valign="middle" align="right" width="40%">From :td> <td valign="middle"
width="60%"><input name="txtSender" type="text" id="txtSender" tabindex="1" style="font-family:Verdana;font-size:X-Small;width:350px;" />td>
tr>
<tr>
<td valign="middle" align="right">To :td>
<td><input name="txtReceiver" type="text" id="txtReceiver" tabindex="1" style="font-family:Verdana;font-size:X-Small;width:350px;" />td>
tr>
<tr>
<td valign="middle" align="right">Cc :td>
<td><input name="txtCc" type="text" id="txtCc" tabindex="1" style="font-family:Verdana;font-size:X-Small;width:350px;" />td>
tr>
<tr>
<td valign="middle" align="right">Bcc :td>
<td><input name="txtBcc" type="text" id="txtBcc" tabindex="1" style="font-family:Verdana;font-size:X-Small;width:350px;" />td>
tr> <tr>
<td valign="middle" align="right">Subject :td>
<td><input name="txtSubject" type="text" id="txtSubject" tabindex="2" style="font-family:Verdana;font-size:X-Small;width:350px;" />td>
tr>
<tr>
<td valign="middle" align="right">Format :td>
<td><table id="rblMailFormat" border="0">
        <tr>
               <td><input id="rblMailFormat_0" type="radio" name="rblMailFormat" value="Text" checked="checked" tabindex="3" /><label for="rblMailFormat_0">Textlabel>td><td><input id="rblMailFormat_1" type="radio" name="rblMailFormat" value="HTML" tabindex="3" /><label for="rblMailFormat_1">HTMLlabel>td>
        tr>
table>td>
tr>
<tr>
<td valign="middle" align="right">Message :td>
<td height="84"> <p><textarea name="txtBody" rows="5" cols="40" id="txtBody" tabindex="4" style="font-family:Verdana;font-size:X-Small;width:350px;">textarea>p> td>
tr>
<tr>
<td valign="middle" align="right">Attachment :td><td><input name="inpAttachment1" type="file" id="inpAttachment1" tabindex="5" size="53" />td> tr>
<tr>
<td align="center" colspan="2"><input type="submit" name="btnSend" value="Send" id="btnSend" tabindex="9" style="width:100px;" />td>
tr>
<tr>
<td align="center" colspan="2"><span id="lblMessage">span>
td>
tr>
table>
td> tr> table>
    form>








Code behind Default.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Net.Mail;

using System.IO;

using System.Drawing;

………………………….

protected void btnSend_Click(object sender, EventArgs e)

{

try

{

/* Create a new blank MailMessage with the from and to

adreesses*/

MailMessage mailMessage = new MailMessage(txtSender.Text, txtReceiver.Text);

/*Checking the condition that the cc is empty or not if

not then * include them

*/

if (txtCc.Text != null && txtCc.Text != string.Empty)

{

mailMessage.CC.Add(txtCc.Text);

}

/*Checking the condition that the Bcc is empty or not

if not then

* include them

*/

if (txtBcc.Text != null && txtBcc.Text != string.Empty)

{

mailMessage.Bcc.Add(txtBcc.Text);

}

//Ading Subject to the Mail

mailMessage.Subject = txtSubject.Text;

//Adding the Mail Body

mailMessage.Body = txtBody.Text;

/* Set the properties of the MailMessage to the

values on the form as per the mail is HTML formatted or plain text */

if (rblMailFormat.SelectedItem.Text ==

"Text")

mailMessage.IsBodyHtml = false;

else

mailMessage.IsBodyHtml = true;

/* We use the following variables to keep track of

attachments and after we can delete them */

string attach1 = null;

string attach2 = null;

string attach3 = null;

/*strFileName has a attachment file name for

attachment process. */

string strFileName = null;

/* Bigining of Attachment1 process & Check the first open file dialog for a attachment */

if (inpAttachment1.PostedFile != null)

{

/* Get a reference to PostedFile object */

HttpPostedFile attFile = inpAttachment1.PostedFile;

/* Get size of the file */

int attachFileLength = attFile.ContentLength;

/* Make sure the size of the file is > 0 */

if (attachFileLength > 0)

{

/* Get the file name */

strFileName = Path.GetFileName(inpAttachment1.PostedFile.FileName);

/* Save the file on the server */

inpAttachment1.PostedFile.SaveAs(Server.MapPath(strFileName));

/* Create the email attachment with the uploaded file

*/

Attachment attach = new

Attachment(Server.MapPath(strFileName));

/* Attach the newly created email attachment */

mailMessage.Attachments.Add(attach);

/* Store the attach filename so we can delete it later

*/

attach1 = strFileName;

}

}

/* Set the SMTP server and send the email with attachment */

SmtpClient smtpClient = new SmtpClient();

smtpClient.Host = "smtp.gmail.com";

smtpClient.Port = 465;

smtpClient.Credentials = new System.Net.NetworkCredential(txtUserName.Text, txtPassword.Text);

//this will be the true in case of gamil and it varies

//from the service provider

smtpClient.EnableSsl = true;

smtpClient.Send(mailMessage);

/* Delete the attachements if any */

try

{

if (attach1 != null)

File.Delete(Server.MapPath(attach1));

}

catch { }

/* clear the controls */

txtSender.Text = string.Empty;

txtReceiver.Text = string.Empty;

txtCc.Text = string.Empty;

txtBcc.Text = string.Empty;

txtSubject.Text = string.Empty;

txtBody.Text = string.Empty;

txtUserName.Text = string.Empty;

/* Dispaly a confirmation message to the user. */

lblMessage.Visible = true;

lblMessage.ForeColor = Color.Black;

lblMessage.Text = "Message sent.";

}

catch (Exception ex)

{

/* Print a message informing the user about the exception that was risen */

lblMessage.Visible = true;

lblMessage.ForeColor = Color.Red;

lblMessage.Text = ex.ToString();

}

}


Happy Coding