News
IBM to offer mobile security as a service IBM will start delivering mobile security-as-a-service (MaaS) through its own cloud infrastructure in India, a move that is expected to better address in-country data requirements... IBM Spectrum Computing: IBM has enlarged its portfolio of software-defined infrastructure solutions with cognitive features for workload management.  * LiFi internet technology has been introduced, the new type of wireless internet connection that gives 100 times faster than traditional WiFi -- Invented by Professor Harald Haas from the University of Edinburgh. * Sci. Rachid Yazami has developed a smart chip that charges smartphones in less than 10 minutes. BenQ has launched BlueCore projector - Consumer electronics major BenQ has launched its first BlueCore laser light source projector. For those unaware, devices with BlueCore laser technology have a high contrast output of 80000:1 with an extended lamp life and efficiency. *** 
  Dec 14 2014 8:30AM     Pragathi
  0 Comments    1599 Views  
Here Pragathi provided a short tutorial to send Email with attachment in ASP.Net using C#/VB
HTML
Below is the sample HTML code,

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <h2>
        Compose Mail</h2>
    <div>
        <table>
            <tr>
                <td>
                    <span>To:</span>
                </td>
                <td>
                    <asp:TextBox ID="txtReceiver" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <br >
                </td>
            </tr>
            <tr>
                <td>
                    <span>Subject:</span>
                </td>
                <td>
                    <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <br >
                </td>
            </tr>
            <tr>
                <td>
                    <span>Body:</span>
                </td>
                <td>
                    <asp:TextBox ID="txtBody" TextMode="MultiLine" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <br >
                </td>
            </tr>
            <tr>
                <td>
                    <span>Attachment: </span>
                </td>
                <td>
                    <asp:FileUpload ID="fileAttachment" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    <br >
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
                </td>
                <td>
                    <asp:Label ID="lblMessage" runat="server"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Namespaces
You will need to import the following namespace.
C#

using System.Net.Mail;
using System.IO;

VB

Imports System.Net.Mail
Imports System.IO

Code for SEND Button
Below is the sample code for SEND button "btnSend_Click" Click Event in ASP.Net C#/VB.
C#

protected void btnSend_Click(object sender, EventArgs e)
{
            bool result = sendmail(txtReceiver.Text.Trim(), txtSubject.Text.Trim(), txtBody.Text.Trim());

            if (result)
                lblMessage.Text = "Email Sent successfully.";
            else
                lblMessage.Text = "Email Sending failed.";
}

VB

Protected Sub btnSend_Click(sender As Object, e As EventArgs)

         Dim result As Boolean = sendmail(txtReceiver.Text.Trim(), txtSubject.Text.Trim(), txtBody.Text.Trim())

         If result Then
              lblMessage.Text = "Email Sent successfully."
         Else
              lblMessage.Text = "Email Sending failed."
         End If

End Sub

Method for Sending E-Mail with Attachment
Below is the sample code for Send E-Mail Method in ASP.Net C#/VB. This methods gets the parameter Receiver MailID, Subject and Body text.
Create a folder with name "attachments" in the project to save the uploaded file.
C#

public bool sendmail(string recievermailid, string subject, string bodyText)
{
            try
            {
                string senderId = "********"// Sender EmailID
                string senderPassword = "*******"// Sender Password      

                bool IsAttachment = false;
                string FileName = string.Empty;
                System.Net.Mail.Attachment attachment = null;        

                System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
                mailMessage.To.Add(recievermailid);
                mailMessage.From = new MailAddress(senderId);

                mailMessage.Subject = subject;
                mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;

                mailMessage.Body = bodyText;
                mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                mailMessage.IsBodyHtml = false;

                if(fileAttachment.HasFile)
                {
    // Save attached file in Server path, will delete later
                    FileName = Path.GetFileName(fileAttachment.PostedFile.FileName);
                    FileName = "attachments/" + FileName;
                    fileAttachment.PostedFile.SaveAs(Server.MapPath(FileName));

                attachment = new System.Net.Mail.Attachment(Server.MapPath(FileName));
                mailMessage.Attachments.Add(attachment);
                
                IsAttachment = true;
                }

                mailMessage.Priority = MailPriority.High;

                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Credentials = new System.Net.NetworkCredential(senderId, senderPassword);
                smtpClient.Port = 587;
                smtpClient.Host = "smtp.gmail.com";
                smtpClient.EnableSsl = true;                

                object userState = mailMessage;

                try
                {
                    smtpClient.Send(mailMessage);

    // Delete saved file in serer folder
                     if (IsAttachment)
                    {
                        attachment.ContentStream.Close();
                        File.Delete(Server.MapPath(FileName));
                    }
                    return true;
                }
                catch (System.Net.Mail.SmtpException)
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
}

VB

Public Function sendmail(recievermailid As String, subject As String, bodyText As StringAs Boolean
       Try
                Dim senderId As String = "********"
                ' Sender EmailID
                Dim senderPassword As String = "*******"
                ' Sender Password      
                Dim IsAttachment As Boolean = False
                Dim FileName As String = String.Empty
                Dim attachment As System.Net.Mail.Attachment = Nothing

                Dim mailMessage As New System.Net.Mail.MailMessage()
                mailMessage.[To].Add(recievermailid)
                mailMessage.From = New (senderId)

                mailMessage.Subject = subject
                mailMessage.SubjectEncoding = System.Text.Encoding.UTF8

                mailMessage.Body = bodyText
                mailMessage.BodyEncoding = System.Text.Encoding.UTF8
                mailMessage.IsBodyHtml = False

                If fileAttachment.HasFile Then
                        ' Save attached file in Server path, will delete later
                        FileName = Path.GetFileName(fileAttachment.PostedFile.FileName)
                        FileName = "attachments/" & FileName
                        fileAttachment.PostedFile.SaveAs(Server.MapPath(FileName))

                        attachment = New System.Net.Mail.Attachment(Server.MapPath(FileName))
                        mailMessage.Attachments.Add(attachment)

                        IsAttachment = True
                End If

                mailMessage.Priority = MailPriority.High

                Dim smtpClient As New SmtpClient()
                smtpClient.Credentials = New System.Net.NetworkCredential(senderId, senderPassword)
                smtpClient.Port = 587
                smtpClient.Host = "smtp.gmail.com"
                smtpClient.EnableSsl = True

                Dim userState As Object = mailMessage

                Try
                        smtpClient.Send(mailMessage)

                        ' Delete saved file in serer folder
                        If IsAttachment Then
                                attachment.ContentStream.Close()
                                File.Delete(Server.MapPath(FileName))
                        End If
                        Return True
                Catch generatedExceptionName As System.Net.Mail.SmtpException
                        Return False
                End Try
       Catch generatedExceptionName As Exception
                Return False
       End Try

End Function

Finally, if you are facing any issue like "The SMTP server requires a secure connection or the client was not authenticated". For that, you should enable application to access gmail account. Please Click Here to Solve.
Result
Result and Page design as Shown Below,
I hope this page will helps to send E-Mail in ASP.Net application. Thanks.
BackToTop
Comments



 
Search
Recent Posts
Create Amazon ElasticCache Using Memcached in CSharp
Oct 29 2018 12:09PM Posted By Amose
Get Google Map Lat Lng (Geo Point) By Pincode in C#
Oct 28 2018 12:09PM Posted By Pranav
Google URL Shortener in C#
Oct 20 2018 12:09PM Posted By Sanjay
Bind Gridview from CSV file in Asp.Net C#
Oct 5 2018 12:09PM Posted By Michael
Call WebService method from jQuery in every 1 minute
Sep 26 2018 12:09PM Posted By John
Gridview custom CSS in ASP.Net
Sep 14 2018 12:09PM Posted By Micheal Ryan
Read excel file and bind to Gridview in C#
Sep 10 2018 12:09PM Posted By Micheal
Tags
Follow us on Facebook
Follow us on Google +
Recent post in your Email inbox.
Enter your email address: