I am currently providing a form in MVC3 for a user to fill in some fields and attach a file. On submission, I send the information posted (with the attachment) twice... one to the poster as a receipt, and the second to another target email.
The issue that I am having is the first email gets sent successfully with the right attachemnt. The second email gets sent out with an attached file that is 0 in size. It seems that after I make an attachment object from a file upload, I cannot reuse it again. Using the debugger I can see that the file upload object is still in memory, buts its ContentLength becomes 0.
So in the following example, if I simplify my code as follows:
public static void SendDummyEmail1()
{
using (var mailMessage = new MailMessage("from@email.com", "to@email.com"))
{
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);
}
If I was to call the above method twice in a row, the first email will go through successfully. The second email will go through but with no attachment because the ContentLength goes to 0.
SendDummyEmail1();
SendDummyEmail1();