+2 votes

Hello,

I am working on save local Draft into email account. I have referred some links and I found following way to attach file in attachment.

byte[] data = ...;
string contentType = ...;
string fileName = ...;
MimeData mime = new MimeFactory().CreateMimeData();
mime.Data = data;
mime.ContentType = ContentType.Parse(contentType);
mime.FileName = fileName 

Here, there are many types of ContentType. If I want to add attachment of Excel file(Ex. abc.xlsx), I must need to check extension from file name manually and compare with ContentType.
My draft attachments are in database as byte array.
Is there any easier way that provide ContentType on the base of file name?

by (3.0k points)
retagged by

1 Answer

0 votes

You can use MimeData.SetFileName method - it can automatically recognize most common extensions.

Excel extensions result in following content-types:

xls -> application/vnd.ms-excel
xlsx -> application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Also adding an attachment is much easier:

// Use builder class to create new email message
MailBuilder builder = new MailBuilder();
// ...
builder.Subject = "Test";

byte[] data = new byte[]{ 1, 2, 3};
MimeData attachment = builder.AddAttachment(data);

attachment.SetFileName("spreadsheet.xls", true);

IMail email = builder.Create();
by (297k points)
Hello,
I have tried "attachment.SetFileName("spreadsheet.xls", true);" but there is no such method like "SetFileName" is available in MimeData Class. I don't know if I am missing something.
Hmm, you are correct - it seems it's not released yet.  It will be available in the next release.
So, how can I manage attachment from database? It there any other way?
You need to set ContentType property by yourself:

attachment.ContentType = new ContentType(
    MimeType.Application,
    MimeSubtype.VndMsExcel);

-or-

attachment.ContentType = new ContentType(
    MimeType.Application,
    new MimeSubtype("vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
New version was just released so you can now use SetFileName method.
Ok. I will definitely try and let you know the result. Thank you for inform.
...