0

I have multiple images in folder but i want some images send in attachment.I have arraylist which contains file names and i want to pass this arraylist items to filepaths but it's not working.filess are not accessible outside the loop. Please help me, Thank you

myMail.Subject = pSubject;
myMail.Body = "Hi ,your event ID is " + pBody;
string[] filePaths = Directory.GetFiles(@"D:\test");
ArrayList list = new ArrayList(27);
list.Add ("12");
list.Add ("1288");
list.Add("1232");
list.Add("1222");
list.Add("1099");

foreach (string listitem in list )
{
 var filess = filePaths.Where(x => 
                  Path.GetFileName(x).Contains(listitem));
}

// Loop through the files enumeration and attach each file in 
//the mail.
foreach (var file in filess)
{
    var attachment = new 
    System.Web.Mail.MailAttachment(file);
    myMail.Attachments.Add(attachment);
}

System.Web.Mail.SmtpMail.SmtpServer = 
"smtp.gmail.com:465";
System.Web.Mail.SmtpMail.Send(myMail);
VDWWD
  • 35,079
  • 22
  • 62
  • 79
don
  • 65
  • 2
  • 10
  • Please explain "Not working". Are there errors? Is the mail not send? Are there no attachments etc? – VDWWD Apr 04 '19 at 19:45
  • Hi,Please check updated question.I am not able to access `filess` variable outside the loop. – don Apr 04 '19 at 19:48
  • You usually cannnot outside the root of the app. The IIS AppPool does not have the privileges. You could enable it but it would be a huge security risk. So put the folder in a subdir of the website. – VDWWD Apr 04 '19 at 20:16
  • hi,this is local directory,i am using this for testing,i will get images from server path after it – don Apr 04 '19 at 20:18

1 Answers1

0

You can check my answer here for a complete snippet to send mail with attachment. But here is the code for reading all files in a folder and adding them as an attachment. Bu the files must be in the root folder of the website!

//find all files in a directory relative to the root folder of the website
string[] files = Directory.GetFiles(Server.MapPath("/images"));

//loop all files in an directory
foreach (var file in files)
{
    //add the file from the fileupload as an attachment
    var stream = new FileStream(file, FileMode.Open);
    message.Attachments.Add(new Attachment(stream, Path.GetFileName(file)));
}
VDWWD
  • 35,079
  • 22
  • 62
  • 79