C# 使用System.Net.Mail发送带有附件的电子邮件
我正在使用System.Net.Mail通过我的应用程序发送电子邮件。我试图发送带有以下代码的附件的电子邮件C# 使用System.Net.Mail发送带有附件的电子邮件,c#,c#-2.0,smtpclient,C#,C# 2.0,Smtpclient,我正在使用System.Net.Mail通过我的应用程序发送电子邮件。我试图发送带有以下代码的附件的电子邮件 Collection<string> MailAttachments = new Collection<string>(); MailAttachments.Add("C:\\Sample.JPG"); mailMessage = new MailMessage(); foreach (string filePath in emai
Collection<string> MailAttachments = new Collection<string>();
MailAttachments.Add("C:\\Sample.JPG");
mailMessage = new MailMessage();
foreach (string filePath in emailNotificationData.MailAttachments)
{
FileStream fileStream = File.OpenWrite(filePath);
using (fileStream)
{
Attachment attachment = new Attachment(fileStream, filePath);
mailMessage.Attachments.Add(attachment);
}
}
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = SmtpHost;
smtpClient.Send(mailMessage);
using
语句的结尾大括号关闭文件流:
using (fileStream)
{
Attachment attachment = new Attachment(fileStream, filePath);
mailMessage.Attachments.Add(attachment);
} // <-- file stream is closed here
使用此解决方案,.NET库将不得不担心打开、读取和关闭文件。完成…我已删除文件流
using (fileStream)
{
Attachment attachment = new Attachment(fileStream, filePath);
mailMessage.Attachments.Add(attachment);
} // <-- file stream is closed here
Collection<string> MailAttachments = new Collection<string>();
MailAttachments.Add("C:\\Sample.JPG");
mailMessage = new MailMessage();
foreach (string filePath in emailNotificationData.MailAttachments)
{
Attachment attachment = new Attachment(filePath);
mailMessage.Attachments.Add(attachment);
}
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = SmtpHost;
smtpClient.Send(mailMessage);