我目前在MVC3中为用户填写一些字段并附加文件提供了一个表单。在提交时,我将发布的信息(附件)两次发送到海报作为收据,第二次发送到另一个目标电子邮件。无法在多封电子邮件中重复使用电子邮件附件
我遇到的问题是第一封电子邮件成功发送与正确attachemnt。第二封电子邮件会发送一个大小为0的附件。看起来,在我从文件上传中创建附件对象之后,我无法再重复使用它。使用调试器,我可以看到,文件上传对象仍然在内存中,它的击打的ContentLength变为0
所以在下面的例子中,如果我简化了我的代码如下:
public static void SendDummyEmail1()
{
using (var mailMessage = new MailMessage("[email protected]", "[email protected]"))
{
mailMessage.Subject = "Email Subject"
mailMessage.Body = Razor.Parse(template, (dynamic)dynamicTokens);
mailMessage.IsBodyHtml = true;
if (_fileUpload != null && _fileUpload.ContentLength > 0)
{
var attachment = new Attachment(_fileUpload.InputStream, _fileUpload.FileName, MediaTypeNames.Application.Octet);
attachment.ContentDisposition.FileName = Path.GetFileName(_fileUpload.FileName);
mailMessage.Attachments.Add(attachment);
}
SendMail(mailMessage);
}
}
public static void SendMail(MailMessage message)
{
var client = new SmtpClient
{
Host = ConfigurationManager.AppSettings[SmtpHostname],
Port = Convert.ToInt32(ConfigurationManager.AppSettings[SmtpPortNumber]),
UseDefaultCredentials = true,
Credentials = CredentialCache.DefaultNetworkCredentials,
DeliveryMethod = SmtpDeliveryMethod.Network,
EnableSsl = true,
};
// Work around remote certificate validation
// Ref: http://stackoverflow.com/questions/777607/the-remote-certificate-is-invalid-according-to-the-validation-procedure-using
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
client.Send(message);
}
如果我是要连续调用上述方法两次,第一封电子邮件将成功通过。第二个电子邮件会经过,但没有附件,因为的ContentLength变为0
SendDummyEmail1();
SendDummyEmail1();
您已经将文件首次发布到服务器。所以下次请求时没有文件。 – 2013-02-28 10:55:59
按照此链接http://stackoverflow.com/questions/12356817/can-not-attach-multiple-files-in-the-attachment-of-email-in-c-sharp/27705328#27705328 – 2014-12-30 12:22:21