Search This Blog

Wednesday 16 September 2015

Send email in asp.net Or How to Send an Email in ASP.NET Application Or How to send email in asp.net c# Or Send email with multiple attachment in asp.net

Step 1:- SendEmail.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SendEmail.aspx.cs" Inherits="Demo.SendEmail" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Send Email</title>
    <script type="text/javascript">
        function validate() {
            var jFrom = document.getElementById("<%=txtFrom.ClientID %>").value;
            var jTo = document.getElementById("<%=txtTo.ClientID %>").value;

            if (jFrom === "") {

                alert("Please enter the From");
                document.getElementById("<%=txtFrom.ClientID %>").focus();
                return false;
            }

            if (jTo === "") {

                alert("Please enter the To");
                document.getElementById("<%=txtTo.ClientID %>").focus();
                return false;
            }

            return true;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>From</td>
                    <td>
                        <asp:TextBox ID="txtFrom" runat="server" Width="206px"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>To</td>
                    <td>
                        <asp:TextBox ID="txtTo" runat="server" Width="206px"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>CC</td>
                    <td>
                        <asp:TextBox ID="txtCC" runat="server" Width="206px"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>BCC</td>
                    <td>
                        <asp:TextBox ID="txtBCC" runat="server" Width="206px"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Subject</td>
                    <td>
                        <asp:TextBox ID="txtSubject" runat="server" Width="206px"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Attachemnt</td>
                    <td>
                        <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="True" />
                    </td>
                </tr>
                <tr>
                    <td>Body</td>
                    <td>
                        <asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Height="106px" Width="206px"></asp:TextBox></td>
                </tr>
            </table>
            <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
            <asp:Label ID="lblMessage" runat="server" Text="Message" Visible="False"></asp:Label>
        </div>
    </form>
</body>
</html>

Step 2:- SendEmail.aspx.cs

using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.UI;

namespace Demo
{
    public partial class SendEmail : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                btnSend.Attributes.Add("onclick""return validate();");
            }
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage mailMessage = new MailMessage();

                // Sender email id
                mailMessage.From = new MailAddress(txtFrom.Text);

                // Whom to send email id
                mailMessage.To.Add(txtTo.Text);

                if (!string.IsNullOrEmpty(txtCC.Text))
                {
                    // Send the email copy to specified email id
                    mailMessage.CC.Add(txtCC.Text);
                }

                if (!string.IsNullOrEmpty(txtBCC.Text))
                {
                    // This email id is not visible to email receiver.
                    mailMessage.Bcc.Add(txtBCC.Text);
                }

                // Email Subject line
                mailMessage.Subject = txtSubject.Text;

                // Checking the UploadedFiles folder existence
                DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath("UploadedFiles"));

                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }

                // Checking the file have to upload
                if (FileUpload1.HasFiles)
                {
                    foreach (HttpPostedFile httpPostedFile in FileUpload1.PostedFiles)
                    {
                        httpPostedFile.SaveAs(Server.MapPath("~/UploadedFiles/") + Path.GetFileName(httpPostedFile.FileName));
                    }
                }

                // Getting UploadedFiles folder Physical path
                string uplodefile = Request.PhysicalApplicationPath + "UploadedFiles\\";

                // Getting UploadedFiles folder All files in string arrary
                string[] fileList = Directory.GetFiles(uplodefile);

                // Attaching each file to mail message
                foreach (string fileName in fileList)
                {
                    mailMessage.Attachments.Add(new Attachment(fileName));
                }

                // Email Body message
                string body = txtBody.Text;

                mailMessage.Body = body;

                // Allow html tag
                mailMessage.IsBodyHtml = true;

                SmtpClient smtpClient = new SmtpClient();

                // Email host server Ip address
                smtpClient.Host = "smtp.gmail.com";

                // Email host server port address
                smtpClient.Port = 587;

                smtpClient.UseDefaultCredentials = false;

                smtpClient.Credentials = new NetworkCredential("Your Gmail Id""Your Gmail Id Password");

                smtpClient.EnableSsl = true;

                smtpClient.Send(mailMessage);

                smtpClient.Dispose();

                lblMessage.Visible = true;
                lblMessage.ForeColor = Color.Green;
                lblMessage.Text = "Email sent successfully";
            }
            catch (Exception exception)
            {
                lblMessage.Visible = true;
                lblMessage.ForeColor = Color.Red;
                lblMessage.Text = "Email not send. Error Occured. " + exception.Message;
            }
        }
    }
}

Step 3:- Result





Note:-

1. This demo is based on .Net 4.5 framework.
2. Don't forgot to add a folder named as UploadedFiles in your project directory.
3. I have used the AllowMultiple="True" property of FileUpload Control to select the multiple files at a time.


No comments:

Post a Comment