" 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_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)