2009-09-22 77 views
2

如何使用c#在電子郵件中附加多個文件。使用C#的電子郵件中的多個附件文件

 MailMessage mail = new MailMessage(); 
     SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); 

     //get the userID, Pass 
     userID= register.userName; 
     password = register.pass; 


     string aa=txtTo.Text; 
     mail.From = new MailAddress(userID); 
     mail.To.Add(aa); 
     mail.Subject = txtsubject.Text; 
     mail.Body = txtComments.Text; 

     //Attach file 
     mail.Attachments.Add(new Attachment(txtAttachments.Text.ToString()));  
     SmtpServer.Port = 587; 
     SmtpServer.UseDefaultCredentials = false; 
     SmtpServer.Credentials = new System.Net.NetworkCredential(userID, password); 
     SmtpServer.EnableSsl = true; 
     SmtpServer.Send(mail); 
     MessageBox.Show("Email sent successfully"); 
     this.Cursor = Cursors.Default; 

     //close the page 
     Email email = new Email(); 
     email.Close(); 

此代碼僅用於附加一個文件。我如何在C#2008中附加多個文件? Plz給我解決方案。

回答

4
... 
mail.Body = txtComments.Text; 
//Attach file 
mail.Attachments.Add(new Attachment(txtAttachments.Text.ToString())); 
mail.Attachments.Add(new Attachment(txtAttachments2.Text.ToString())); 
mail.Attachments.Add(new Attachment(txtAttachments3.Text.ToString())); 
mail.Attachments.Add(new Attachment(txtAttachments4.Text.ToString())); 
SmtpServer.Port = 587; 
...  
+1

任何完整的源代碼示例? – Kiquenet 2013-08-19 11:34:25

+0

@David如何才能添加動態數量的附件? – NuWin 2016-09-09 16:33:09

4

多個附件可以被添加到集合Message.Attachments

C#:

Message.Attachments.Add(new System.Net.Mail.Attachment(strAttPath)); 

VB:

Message.Attachments.Add(New Net.Mail.Attachment(strAttPath)) 

要獲取.Add多次,指向每個附件。

+1

非常感謝!你幫我解決這個問題。 +1 - 我編輯你的問題(對不起),因爲你的解決方案是在VB中,我必須將它翻譯成C#,因爲這個問題是評論。但無論如何非常感謝! – 2013-02-28 13:24:57

2

只需在上面添加更多附件到mail.Attachments集合即可。

1

怎樣在發送後釋放附件文件?

例如,您發送用於創建附件內容的臨時文件。爲了這個目的,這個文件被重複使用。該附件文件需要在附件上發佈dispose()

要完成此操作,請先創建附件,然後再爲其指定一個對象名,以便與dispose()一起使用。

Attachment attach = new Attachment(txtAttachments.Text.ToString());  
Message.Attachments.Add(attach); 
... 

attach.dispose();