Attachment start missing in an Email after a perio

2019-06-22 08:59发布

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.

1条回答
贼婆χ
2楼-- · 2019-06-22 09:06

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
查看更多
登录 后发表回答