Generate EML Content ( Add file as an attachment)

45 views Asked by At

I am trying to implement email functionality on JavaScript based front end. My task is to open default email client (mostly outlook) with an attachment (file). I used mailto, but it doesn't support attachments. Now instead of getting downloaded file as a blob from server, i am trying to get eml based blob, download it, and I assume it will open successfully in outlook with attachment. I am not very well versed in backend ( c# ), so any help will be appreciated. I have this code which gets me the downloaded file path

var fileDetail = await service.DownloadFile(id);

var bytes = File.Exists(fileDetail.Path);

var stream = new MemoryStream(bytes);
return File(stream, fileDetail.MimeType, fileDetail.DownloadFileName);



FileDetail contains filePath, mimeType, fileName etc. This file can be pdf, tiff or any text file.

My aim is to generate an email file with the attached file above that i get ( no need of recipent,subject etc) . Do proper mime type for email, and send it to front end for download.

1

There are 1 answers

4
Dmitry Streblechenko On BEST ANSWER

In case of a plain text + attachment, make the main part Content-Type: multipart/mixed, convert the attachment data to base 64

byte[] fileBytes = File.ReadAllBytes(filePath);
string base64String = Convert.ToBase64String(fileBytes);

add two parts to the MIME message: one text/plain, another application/octet-stream with the base 64 encoded file data (see below).

As a test, your can create a test EML message by drafting it in Outlook and sending ti to a Gmail mailbox - you can then look at the raw MIME source of the message in your Gmail mailbox. Or you can convert any message in Outlook to MIME using OutlookSpy (I am its author) - open or select a message, click IConverterSession button on the OutlookSopy ribbon, click MAPIToMIMEStm.

From: "It's Siddiqi" <[email protected]>
To: <[email protected]>
Subject: test
MIME-Version: 1.0
Content-Type: multipart/mixed;
    boundary="----=_NextPart_000_001A_01DA7B03.A146C8E0"
Content-Language: en-us

This is a multipart message in MIME format.

------=_NextPart_000_001A_01DA7B03.A146C8E0
Content-Type: text/plain;
    charset="us-ascii"
Content-Transfer-Encoding: 7bit

Test body

------=_NextPart_000_001A_01DA7B03.A146C8E0
Content-Type: application/octet-stream;
    name="test.bin"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
    filename="test.bin"

5XAGkAbgBkAG...
...<youyr base 64 data>
AAoADQAKAA==

------=_NextPart_000_001A_01DA7B03.A146C8E0--