Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Send email with attachment using Gmail SMTP Server in ASP.Net

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 260
    Comment on it

    " Send email with attachment using Gmail SMTP Server in ASP.Net. "

        In this article I will discuss how to integrate the email functionality along with the attachment in a Asp.Net Application.

    Getting Started:

    Step 1: Create a web application.

    Step 2: Take a File upload control and a Button as follows:

    <asp:FileUpload ID="fuAttachment" runat="server" />
    
     <asp:Button ID="Button1" runat="server" Text="Send Mail" OnClick="Button1&#95;Click" />
    

    Step 3: Now on click event ("Button1_Click") add the following code:

     using (MailMessage mm = new MailMessag("Sender's EmailAddress","Reciever's EmailAddress"))
      {
        mm.Subject = "Subject of the Email";
        mm.Body = "Main content of the Email";
    
        if(fuAttachment.HasFile)
         {
           string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
           mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
         }
    
        mm.IsBodyHtml = false;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = new NetworkCredential("Sender's EmailAddress","Sender's   
    
       Password");
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
        ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
    
      } 
    

    In the above code, the following code will attach the file to the mail:

     if(fuAttachment.HasFile)
         {
           string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
           mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
         }
    

    When the mail is sent the Following Line will show an alert of "Email Sent":

    ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
    

    Hope it helps...!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: