2009-09-22 6 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(); 

このコードは1つのファイルのみを添付するために使用されます。どのように私はC#2008で複数のファイルを添付することができますか? Plz私に解決策を教えてください。

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

VB:

答えて

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

+0

@Davidどのように動的量の添付ファイルを追加することができますか? – NuWin

4

複数の添付ファイルは、Message.Attachmentsコレクション

のC#に追加することができ

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

単に各アタッチメントを指し、.Add複数回呼び出します。

+1

ありがとう!あなたはこれで私を助けます。 +1 - あなたの解決策がVBであったので私はあなたの質問を(私を許して)編集する、私はそれをC#に翻訳しなければならない質問が注目される。しかし、とにかくおかげさまで! –

2

上記のように、添付ファイルをmail.Attachmentsコレクションに追加するだけです。

1

送信後に添付ファイルを解放するとどうなりますか?

たとえば、添付ファイルのコンテンツの作成に使用された一時ファイルを送信します。このファイルは、この目的のために繰り返し使用されます。添付ファイルは、添付ファイルにdispose()で公開する必要があります。

これを達成するには、あとでdispose()で使用するオブジェクト名を添付ファイルとして最初に作成します。

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

attach.dispose(); 
関連する問題