使用C#的电子邮件中的多个附件文件
问题描述:
如何使用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给我解决方案。
答
...
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;
...
答
多个附件可以被添加到集合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
答
只需在上面添加更多附件到mail.Attachments集合即可。
答
怎样在发送后释放附件文件?
例如,您发送用于创建附件内容的临时文件。为了这个目的,这个文件被重复使用。该附件文件需要在附件上发布dispose()
。
要完成此操作,请先创建附件,然后再为其指定一个对象名,以便与dispose()一起使用。
Attachment attach = new Attachment(txtAttachments.Text.ToString());
Message.Attachments.Add(attach);
...
attach.dispose();
任何完整的源代码示例? – Kiquenet 2013-08-19 11:34:25
@David如何才能添加动态数量的附件? – NuWin 2016-09-09 16:33:09