Friday, 6 July 2012

Sending email with attachment in ASP.NET


Introduction
In this article, I am describe how to send email with attachment in ASP.NET using System.IO, System.Net and System.Net.Mail namespaces in this article.
In ASP.NET, sending emails has become simpler. The classes required to send an email are contained in the System.Net.Mail. The steps required to send an email with attachment from ASP.NET are as follows: Below is sample code showing how to send email with attachment from ASP.Net using C#. With this code send main from Gmail SMTP server you can also configure your own SMTP server to change in web config file.
To configure SMTP configuration data for ASP.NET, you would add the following tags to your web.Config file.
 
<system.net>
  <mailSettings>
    <smtp from="YourEmailid@gmail.com" deliveryMethod="Network">
      <network host="smtp.gmail.com" port="587"  
               userName="YourEmailid@gmail.com"
               password="yourPassword"/>
    smtp>
  mailSettings>
system.net>      

<%@ Page Language="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"%>

DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Pagetitle>
    <style type="text/css">
        table.hovertable
        {
            font-family: verdana,arial,sans-serif;
            font-size: 11px;
            color: #333333;
            border-width: 1px;
            border-color: #999999;
            border-collapse: collapse;
        }
        table.hovertableth
        {
            background-color: #c3dde0;
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #a9c6c9;
        }
        table.hovertabletr
        {
            background-color: #d4e3e5;
        }
        table.hovertabletd
        {
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #a9c6c9;
        }
    style>

    <script type="text/javascript">
    functionEmailvalidation()
    {
       if(document.getElementById("txtBoxTo").value=="")
       {
         alert('Please Enter Email ID');
         document.getElementById("txtBoxTo").focus();
         returnfalse;
       }
       varemailPat = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;   
       varemailid=document.getElementById("txtBoxTo").value;
       varmatchArray = emailid.match(emailPat);
       if(matchArray == null)
       {          
           alert('Please Enter Correct Email ID');
           document.getElementById("txtBoxTo").focus();            
           returnfalse;
                 
       }
       if(document.getElementById("txtBoxCC").value=="")
       {
         alert('Please Enter Email ID');
         document.getElementById("txtBoxCC").focus();
         returnfalse;
       }
       varemailPat = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;   
       varemailid=document.getElementById("txtBoxCC").value;
       var matchArray = emailid.match(emailPat);
       if(matchArray == null)
       {          
           alert('Please Enter Correct Email ID');   
           returnfalse;                    
       }
    }
    script>

head>
<body>
    <form id="form1" runat="server">
    <div>
        <table class="hovertable" align="center" width="44%">
            <tr>
                <td>
                    To
                td>
                <td>
                    <asp:TextBox ID="txtBoxTo" runat="server">asp:TextBox>
                td>
            tr>
            <tr>
                <td>
                    CC
                td>
                <td>
                    <asp:TextBox ID="txtBoxCC" runat="server">asp:TextBox>
                td>
            tr>
            <tr>
                <td>
                    Subject
                td>
                <td>
                    <asp:TextBox ID="txtBoxSubject" runat="server">asp:TextBox>
                td>
            tr>
            <tr>
                <td>
                   Attachment
                td>
                <td>
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                td>
            tr>
            <tr>
                <td>
                    Message
                td>
                <td>
                    <asp:TextBox ID="txtareaMessage" runat="server" TextMode="MultiLine">asp:TextBox>
                td>
            tr>
            
            <tr>
                <td>
                     
                td>
                <td>
                     
                td>
            tr>
            <tr>
                <td colspan="2" align="center">
                    <asp:Button ID="btnSend" runat="server" Text="Send" OnClientClick="return Emailvalidation()"
                        OnClick="btnSend_Click" />
                td>
            tr>
            <tr>
                <td>
                     
                td>
                <td>
                     
                td>
            tr>
        table>
    div>
    form>
body>
html>

using System;
usingSystem.Configuration;
usingSystem.Data;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.HtmlControls;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Xml.Linq;
usingSystem.Net.Mail;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(objectsender, EventArgs e)
    {

    }
    protected void btnSend_Click(objectsender, EventArgs e)
    {
        SmtpClientsmtp = new SmtpClient();
        MailMessagemsg = new MailMessage();
        smtp.EnableSsl = true;
        msg.IsBodyHtml = true;
        msg.To.Add(newMailAddress(txtBoxTo.Text));
        if(txtBoxCC.Text != "")
            msg.CC.Add(newMailAddress(txtBoxCC.Text));
        msg.Subject = txtBoxSubject.Text;
        msg.Body = txtareaMessage.Text;
        if(FileUpload1.PostedFile.ContentLength > 0)
        {
            Attachmentattachment = new Attachment(Path.GetFullPath(FileUpload1.PostedFile.FileName));
            msg.Attachments.Add(attachment);
        }
        smtp.EnableSsl = true;
        objectstate = msg;
        smtp.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
        smtp.Send(msg);
        fnAlert("Email Sent Successfully.");
    }

    private static voidsmtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgse)
    {
        MailMessagemail = e.UserState as MailMessage;
        if(!e.Cancelled && e.Error != null)
        { }
        else
        { }
    } 

}


Conclusion:

In this article, we explored how easy it is to send Email’s using the classes in System.Net.Mail. This approach of sending mails will remain the same for web as well as windows application.

Downloads
You can download the complete source code in  C# .

Send_Email_With_Attachement_Using_Gmail.zip

3 comments:

Bhaskara said...

easy to understand .thanks,

www.aspdotnet-sharepoint.com

Suba said...

Dot Net is an ever trending technology where it is more preferable by developers to utilize the features in the dot net language. Your article on Dot Net language proves that it is an evergreen technology in the IT market.
Regards:
DOT NET Course Chennai | DOT NET Training Institute in Chennai

Janu said...

Good job in presenting the correct content with the clear explanation. The content looks real with valid information. Good Work




Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery




Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Powered by Blogger