收集txt文件并通过电子邮件发送

时间:2013-10-06 08:08:15

标签: email c#-4.0 email-attachments

大家好我还在学习c#我需要帮助以下我试图搜索目录并收集txt文件然后通过电子邮件将其作为附件发送。                {

                    MailMessage mail = new MailMessage();
                    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                    mail.From = new MailAddress("******");
                    mail.To.Add("********");
                    mail.Subject = "Test Mail - 1";
                    mail.Body = "mail with attachment";


                    string folder = @"C:\files";
                    string[] txtfiles = Directory.GetFiles(folder, "*.txt");


                    *foreach( txtfiles in folder )*  
                      // this where my problem lies im trying to loop through directory                   //files and then add as attachment

                    {

                    System.Net.Mail.Attachment attachment;
                    attachment = new System.Net.Mail.Attachment(folder);
                    mail.Attachments.Add(attachment);

                    SmtpServer.Port = 587;
                    SmtpServer.Credentials = new System.Net.NetworkCredential("*****", "******");
                    SmtpServer.EnableSsl = true;

                    SmtpServer.Send(mail);


                    }


                    }

                  }

1 个答案:

答案 0 :(得分:0)

你必须在txtfiles上循环而不是变量文件夹。看起来应该是这样的

    foreach (var txtfile in txtfiles)
    {
        mail.Attachments.Add(new System.Net.Mail.Attachment(txtfile);
    }