简体   繁体   中英

Attachment start missing in an Email after a period of time

I am having issues with the attachment in an email. After every few days, user don't find the expected attachment in there email. This seems to be happening for around 10-20 mins and then it corrected itself meaning that the later email will contain the attachments. I am not sure what could be the reason behind this. This is how my code looks like

Model

public class EmailAttachment
{
    public string FileName { get; set; }
    public byte[] FileContent { get; set; }
} 

Code trigger to send an Email

var emailAttachment= new EmailAttachment();
emailAttachment.FileContent = CreatePDFFile();
emailAttachment.FileName = "file.pdf";
EmailGeneratedCertificate(emailAttachment);

Email Preparation Code

public void EmailGeneratedCertificate(EmailAttachment file)
{
    //file.FileContent is a byte array  
    var ms = new MemoryStream(file.FileContent);
    ms.Position = 0;
    var contentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);

    var from = "xx@x.com";
    var fromTargetName = "XXX";
    var recepient="xx2@x.com"
    var subject = "Attachment";
    var body="<strong>Please find attachment.</strong>"
    var attachment = new Attachment(ms, contentType);
    attachment.ContentDisposition.FileName = file.FileName;
    var attachments = new List<Attachment>();
    attachments.Add(attachment);
    _mailService.Send(recepient, null, subject, body, attachments);
}

Another thing I wanted to point out, I have two websites running within a different APP POOL and both have the same email sending code like above and when this issue occur, it seems to be happening on both websites at same time for 10-15 mins and then corrected itself. Please suggest.

In your question you don't write all the code of CreatePDFFile() that IMHO is the cause of the strange behavior so I can only guess from the code you post.

I see 2 main problem:

  1. private byte[] ReadFile(string path) : you are swallowing any exception and if there are some it returns an empty byte array so no attachment.
  2. MemoryStream in EmailGeneratedCertificate(EmailAttachment file) : you are not disposing the stream and this could case some unexpected behavior

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM