Sunday, September 13, 2009

How To Send Mail With Attachment In Asp.Net

have to Include The following Namespace,

using System.Net;
using System.Net.Mail; // For Mailing Purpose
using System.IO;  // To Check File existence in Server
using System.Text; // For Encoding.UTF8

         try
        {
            MailMessage objMailMsg = new MailMessage(txtFrom.Text.Trim(), txtTo.Text.Trim());
            Attachment MailAttachment;

            objMailMsg.BodyEncoding = Encoding.UTF8;
            if (txtCc.Text.Trim().Length > 0)
            {
                objMailMsg.CC.Add(txtCc.Text.Trim());
            }
            if (txtBcc.Text.Trim().Length > 0)
            {
                objMailMsg.Bcc.Add(txtBcc.Text.Trim());
            }
            objMailMsg.Subject = "Testing Mail";
            objMailMsg.Body = txtMessage.Text.Trim();
            if (fuMailAtt.HasFile)
            {
                if (!File.Exists(Server.MapPath(@"Attach\" + fuMailAtt.FileName)))
                {
                    fuMailAtt.SaveAs(Server.MapPath(@"Attach\" + fuMailAtt.FileName));
                    MailAttachment = new Attachment(Server.MapPath(@"Attach\" + fuMailAtt.FileName));
                    objMailMsg.Attachments.Add(MailAttachment);
                }
                else
                {
                    MailAttachment = new Attachment(Server.MapPath(@"Attach\" + fuMailAtt.FileName));
                    objMailMsg.Attachments.Add(MailAttachment);
                }
            }
            objMailMsg.Priority = MailPriority.High;
            objMailMsg.IsBodyHtml = true;

            SmtpClient objSMTPClient = new SmtpClient("smtp.mail.yahoo.com", 587);
            objSMTPClient.Credentials = new NetworkCredential("YourYahooId", "Your Yahoo Password");
            objSMTPClient.Send(objMailMsg);
            Response.Write("Mail Send");
        }
        catch (Exception ex)
        {
            Response.Write("Mail Not Send " + ex.Message);
        }

Controls Name

From Address        txtFrom
To Address            txtTo
Cc Address           
txtCc
Bcc Address          txtBcc
FileUpload             fuMailAtt
Message                txtMessage
Send Button           btnSend

Download SourceCode




No comments:

Creative Commons License
Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.