Attachment start missing in an Email after a period of time

浪尽此生 提交于 2019-12-10 14:29:10

问题


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:


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


来源:https://stackoverflow.com/questions/35294492/attachment-start-missing-in-an-email-after-a-period-of-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!