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.
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:
private byte[] ReadFile(string path)
: you are swallowing any exception and if there are some it returns an empty byte array so no attachment.MemoryStream
in EmailGeneratedCertificate(EmailAttachment file)
: you are not disposing the stream and this could case some unexpected behaviorIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With