I’m convert an svg object to a byte[] and storing this in a queue with the following class
public class MailMessage
{
public string AttachmentName { get; set; }
public byte[] Attachment { get; set; }
}
However the email never gets sent. I’m thinking that the attachment is corrupt because if we skip adding the attachment to the email then it sends fine.
using (var stream = new MemoryStream(attachment))
{
var mailMessage = new MailMessage(this.from, new MailAddress(recipient)) { Subject = subject, Body = message };
// this is the line which if commented out allows the email to be sent
mailMessage.Attachments.Add(new Attachment(stream, filename));
MailSender().SendAsync(mailMessage, null);
}
A co-worker suggested that the byte[] may have been compromised due to the way rabbit stores messages and to therefore base64 encode the byte[] before storing it using the built in functions
Convert.ToBase64String(bytes)
Convert.FromBase64String(message.Attachment) // to retrieve
However that didn’t work either.
Can anyone think why this is failing to send and think of any work-arounds.
I’m contemplating storing the image in the database and deleting it once the email is sent, but this is a last resource.
The issue is with
MailSender.SendAsync(). Thestreamobject is get disposed before the mail is sent.Don’t use “
using” here. You are destroying the memory stream immediatelyafter calling
SendAsync, e.g. probably before SMTP gets to read it(since it’s async).
Either Destroy your stream in the callback.
or
Use
MailSender.Send()instead ofMailSender.SendAsync()to send synchronusly.Refer this for more detail