Share via

How can I drag and Drop and email from Outlook into a web form, and parse out the email details

Ian Hockaday 20 Reputation points
2025-03-21T19:50:20.59+00:00

I have a drag and drop form working, but I cannot get the email details from the 'dropped' file.
Tried using the Microsoft.Office.Interop.Outlook package (had success in a winformapp), but I can't figure it out.

Here is a js snippet I am using to trap the drop event:

const handleDrop = (e) => {

const dt = e.dataTransfer;

const files = dt.files;

const fileArray = [...files];

fileArray.forEach((item) => {

	console.log(item);
```//		Outlook.MailItem mi = (Outlook.MailItem) file;

});

Developer technologies | ASP.NET Core | ASP.NET API
0 comments No comments

Answer accepted by question author

  1. Anonymous
    2025-03-24T07:08:44.4866667+00:00

    Hi @Ian Hockaday,

    but I cannot get the email details from the 'dropped' file

    You cannot drag and drop emails directly from the desktop application to the page. You may need to save the email and then upload it so that the web application receives the file and parses it on the server.

    If you need to parse mail using Microsoft.Office.Interop.Outlook, you can try this sample code (in web form):

    aspx:

    <head runat="server">
        <title>DND File upload</title>
        <style>
            #dropZone {
                width: 300px;
                height: 200px;
                border: 2px dashed #ccc;
                text-align: center;
                line-height: 200px;
                font-family: Arial, sans-serif;
                color: #ccc;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
            <div id="dropZone">Drag and drop files here</div>
            <asp:FileUpload ID="fileUpload" runat="server" />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
            <br />
            <br />
            <asp:Label runat="server" ID="StatusLabel" Text="Upload status: " />
        </form>
        <script>
            var dropZone = document.getElementById('dropZone');
            var fileUpload = document.getElementById('<%= fileUpload.ClientID %>');
            dropZone.addEventListener('dragover', function (e) {
                e.preventDefault();
                dropZone.style.borderColor = '#000';
            });
            dropZone.addEventListener('dragleave', function (e) {
                e.preventDefault();
                dropZone.style.borderColor = '#ccc';
            });
            dropZone.addEventListener('drop', function (e) {
                e.preventDefault();
                dropZone.style.borderColor = '#ccc';
                var files = e.dataTransfer.files;
                if (files.length > 0) {
                    fileUpload.files = files;
                }
            });
        </script>
    </body>
    

    aspx.cs:

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (fileUpload.HasFile)
        {
            try
            {
                // get uploaded file
                HttpPostedFile postedFile = fileUpload.PostedFile;
                string fileName = Path.GetFileName(postedFile.FileName);
    
                
                if (Path.GetExtension(fileName).ToLower() == ".msg")
                {
                    // save file in temp path
                    string tempFilePath = Path.Combine(Server.MapPath("~/"), fileName);
                    postedFile.SaveAs(tempFilePath);
    
                    // Parsing .msg files
                    Application outlookApp = new Application();
                    NameSpace outlookNamespace = outlookApp.GetNamespace("MAPI");
                    MailItem mailItem = outlookApp.Session.OpenSharedItem(tempFilePath) as MailItem;
    
                    if (mailItem != null)
                    {
                        // Extract email information
                        string senderEmail = mailItem.SenderEmailAddress;
                        string senderName = mailItem.SenderName;
                        string subject = mailItem.Subject;
                        string body = mailItem.Body;
    
                        // show info for test
                        Response.Write($"sender: {senderName} &lt;{senderEmail}&gt;<br/>");
                        Response.Write($"Object: {subject}<br/>");
                        Response.Write($"Body: {body}<br/>");
    
                        // Release COM obj
                        Marshal.ReleaseComObject(mailItem);
                    }
                    else
                    {
                        Response.Write("Unable to parse .msg file.");
                    }
    
                    Marshal.ReleaseComObject(outlookNamespace);
                    Marshal.ReleaseComObject(outlookApp);
    
                    // Delete temp file
                    File.Delete(tempFilePath);
                }
                else
                {
                    Response.Write("Please upload a valid .msg file.");
                }
            }
            catch (System.Exception ex)
            {
                Response.Write("Parsing error: " + ex.Message);
            }
        }
    }
    
    

    Best regards,

    Xudong Peng


    If the answer is the right solution, please click "Accept Answer" and kindly upvote. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Danny Nguyen (WICLOUD CORPORATION) 6,865 Reputation points Microsoft External Staff Moderator
    2025-07-23T10:20:49.7366667+00:00

    Hi,

    The issue you're encountering is that when you drag an email from Outlook into a web browser, it doesn't actually transfer the email as a structured object that you can directly access with JavaScript. The files array will contain the email as a file (usually with a .msg extension), but you can't use the Microsoft.Office.Interop.Outlook package in a web context - that's a .NET library that only works in desktop applications.

    I suggest using a Javascript library llike msg-reader to parse Outlook .msg files: https://github.com/Sicos1977/MSGReader

    Here's an example:

    const handleDrop = async (e) => {
        e.preventDefault();
        const dt = e.dataTransfer;
        const files = dt.files;
        const fileArray = [...files];
     
        for (const file of fileArray) {
            console.log('File type:', file.type);
            console.log('File name:', file.name);
            // Check if it's an Outlook message file
            if (file.name.endsWith('.msg') || file.type === 'application/vnd.ms-outlook') {
                try {
                    const arrayBuffer = await file.arrayBuffer();
                    const msgReader = new MsgReader(arrayBuffer);
                    const fileData = msgReader.getFileData();
                    // Extract email details
                    const emailData = {
                        subject: fileData.subject,
                        from: fileData.senderName,
                        to: fileData.recipients,
                        body: fileData.body,
                        date: fileData.creationTime,
                        attachments: fileData.attachments
                    };
                    console.log('Email data:', emailData);
                } catch (error) {
                    console.error('Error parsing .msg file:', error);
                }
            }
        }
    };
    
    
    

    Hope this helps

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

  2. Pradeep M 9,880 Reputation points Microsoft External Staff Moderator
    2025-03-24T06:06:17.4766667+00:00

    Hi Ian Hockaday,

    Thank you for reaching out to Microsoft Q & A forum. 

    When you drag and drop an email from Outlook into a web form, it gets saved as a .msg file, which browsers can't directly read. 

    1.Basic JavaScript Handling  You can capture the dropped file, but extracting its content isn’t possible in the browser alone: 

    const handleDrop = (e) => {  
        e.preventDefault();  
        const file = e.dataTransfer.files[0];  
        console.log("Filename:", file.name);  
    };
    
    

     2.Backend Processing  Since .msg files require special handling, you’ll need to upload the file to a backend and use a library to extract its details: 

    Node.js: msgreader 

    Python: extract-msg 

    3.Outlook API Integration  If you want to fetch email details directly, consider: 

    Microsoft Graph API (For Office 365 emails) 

    EWS (Exchange Web Services) (For Exchange servers) 

    Since Microsoft.Office.Interop.Outlook only works in desktop apps, a backend-based approach is the best solution for web applications.    

    If you have found the answer provided to be helpful, please click on the "Accept answer/Upvote" button so that it is useful for other members in the Microsoft Q&A community.  

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.