How to Send Email with Attachment in ASP.NET

Sending an email with attachment with ASP.NET is easy. The file that will be sent as an attachment in ASP.NET will be uploaded using FileUpload and will be added dynamically as an attachment in the MailMessage object without saving any file in the disk.

Here is the code to send an email with attachment using Gmail SMTP:

For C#:

protected void SendEmail(object sender, EventArgs e)
{
    using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
    {
        mm.Subject = txtSubject.Text;
        mm.Body = txtBody.Text;
        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(txtEmail.Text, txtPassword.Text);
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
        ClientScript.RegisterStartupScript(GetType(), “alert”, “alert(‘Email sent.’);”,true);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *