Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = "[email protected]";
    var fromTargetName = "XXX";
    var recepient="[email protected]"
    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.

like image 922
Ammar Khan Avatar asked Oct 18 '22 16:10

Ammar Khan


1 Answers

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
like image 170
giammin Avatar answered Oct 21 '22 04:10

giammin