Gholamreza Asadi
Gholamreza Asadi

Reputation: 105

how to send email with attachment from server path in asp.net c#

I need to attach files with my email in asp.net. the files are uploaded in the Server.path. but I don't know how to add this with my email please guide me My code

public static void SendEmail_With_Attachment(String ToEmail, String Subj, string Message, string sourcePath)
{
    //reading sender email credential from web.config file
    HostAdd = ConfigurationManager.AppSettings["Host"].ToString();
    FromEmailid = ConfigurationManager.AppSettings["FromMail"].ToString();
    Pass = ConfigurationManager.AppSettings["Password"].ToString();

    //creating the object of mailmessage
    System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
    mailMessage.From = new MailAddress(FromEmailid);
    mailMessage.Subject = Subj;
    mailMessage.Body = Message;
    mailMessage.IsBodyHtml = true;
    mailMessage.To.Add(new MailAddress(ToEmail));
    FileStream fStream;
    DirectoryInfo dir = new DirectoryInfo(sourcePath);
    foreach (FileInfo files in dir.GetFiles("*.*"))
    {
        fStream = File.OpenRead(sourcePath + "\\" + files.Name);
        mailMessage.Attachments.Add(new System.Net.Mail.Attachment(fStream, files.Name));
        fStream.Close();
    }

    SmtpClient smtp = new SmtpClient();
    smtp.Host = HostAdd;

    //network and security related credentia
    smtp.EnableSsl = true;
    NetworkCredential NetworkCred = new NetworkCredential();
    NetworkCred.UserName = mailMessage.From.Address;
    NetworkCred.Password = Pass;
    smtp.UseDefaultCredentials = true;
    smtp.Credentials = NetworkCred;
    smtp.Port = 587;
    smtp.Send(mailMessage);
}

this code working very fine without attachment, bout with attachment i get this error: Failure sending mail.

Upvotes: 1

Views: 9836

Answers (1)

Win
Win

Reputation: 62300

You do not need to Open files.

foreach (FileInfo file in dir.GetFiles("*.*"))
{
   if (file.Exists) 
   {
      mailMessage.Attachments.Add(new Attachment(file.FullName));
   }
}

Upvotes: 2

Related Questions