Search code examples
c#mime

MimeMessage Get Attachment Name


May I know how do I get the name of the attachment in a MimeMessage?

I am unable to locate a name property for the attachment.

Below is my code snippet.

MimeMessage eml = MimeMessage.Load(savedEmlFullFilePath);
EmailMessage mail = new EmailMessage(service);

foreach (var attachment in eml.Attachments)
{
    using (var stream = File.Create(AppConfig.EmailSaveFilePath + "attachment_from_email"))
    {
        if (attachment is MessagePart)
        {
            var part = (MessagePart)attachment;

            part.Message.WriteTo(stream);

            mail.Attachments.AddFileAttachment(AppConfig.EmailSaveFilePath + "attachment_from_email");
        }
        else
        {
            var part = (MimePart)attachment;

            part.Content.DecodeTo(stream);

            mail.Attachments.AddFileAttachment(AppConfig.EmailSaveFilePath + "attachment_from_email");
        }
    }
}

Solution

  • MimePart has a FileName property that you can use.

    MessageParts generally do not have filenames, but if they do, you should be able to use logic like this to get it:

    string fileName = msgPart.ContentDisposition?.FileName ?? msgPart.ContentType.Name;