-1

I am using the code below to export an outlook-mounted .pst file called working to a local MySQL database, for the most part the code works fine however some "Sender_Email and "Received_Email" are displaying in their EX format like the below

/o=ExchangeLabs/ou=Exchange Administrative Group (FYDIBOPDLT)/cn=Recipients/cn=ed403ae50a4581-a.john

this is driving me crazy! the email address should be a.john@domain.com rather than this awkward format, other emails appear fine with the @domain etc just some of them have this awkward format - does anyone know what i need to edit to make this code work correctly ? I included all the code below as I am a beginner and this code wasn't written fully by myself so I would very much appreciate any advise you can give me.

using Microsoft.Office.Interop.Outlook;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Configuration;

namespace ConsoleApp3
{
class Program
{
    static void Main(string[] args)
    {
        try
        {
            var myconn = new MySqlConnection
            ("server = 0.0.0.0;" +
            "user = user;" +
            "database = sys;" +
            "port = 0000;" +
            "password = password;" +
            "Connect Timeout=1;");

            myconn.Open();

            List<MailItem> mailItems = readPst(@"C:\Users\john\Desktop\working.pst", "working");
            int counter = 0;
            int totalMailItemCount = mailItems.Count();
            for (int i = 0; i < mailItems.Count(); ++i)// MailItem mailItem in mailItems)
            {
                var dateTimeSentToInsert = mailItems[i].SentOn.ToString("yyyy-MM-dd H:mm:ss");
                var dateTimeReceivedToInsert = mailItems[i].ReceivedTime.ToString("yyyy-MM-dd H:mm:ss");
                var recipients = "";
                foreach (Recipient recipient in mailItems[i].Recipients)
                {
                    recipients += recipient.Address + "~";
                }

                MySqlCommand command = myconn.CreateCommand();
                command.CommandText = "INSERT INTO mail2 (Sender_Name, Sender_Email, Received_Name, Received_Email, Date_Sent, Date_Received, Subject, Body" +
                    ") VALUES (@sender_name, @sender_email, @received_name, @received_email, @date_sent, @date_received, @subject, @body)";
                command.Parameters.AddWithValue("@sender_name", mailItems[i].SenderName);
                command.Parameters.AddWithValue("@sender_email", mailItems[i].SenderEmailAddress);
                command.Parameters.AddWithValue("@received_name", mailItems[i].ReceivedByName);
                command.Parameters.AddWithValue("@received_email", recipients);
                command.Parameters.AddWithValue("@date_sent", dateTimeSentToInsert);
                command.Parameters.AddWithValue("@date_received", dateTimeReceivedToInsert);
                command.Parameters.AddWithValue("@subject", mailItems[i].Subject);
                command.Parameters.AddWithValue("@body", mailItems[i].Body);
                command.ExecuteNonQuery();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(mailItems[i]);

                Console.WriteLine(++counter + " completed out of " + totalMailItemCount);
            }

            myconn.Dispose();
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.ReadLine();
    }

    private static List<MailItem> readPst(string pstFilePath, string pstName)
    {
        List<MailItem> mailItems = new List<MailItem>();
        Application app = new Application();
        NameSpace outlookNs = app.GetNamespace("MAPI");
        // Add PST file (Outlook Data File) to Default Profile
        MAPIFolder rootFolder = outlookNs.Stores[pstName].GetRootFolder();
        // Traverse through all folders in the PST file
        // TODO: This is not recursive, refactor
        Folders subFolders = rootFolder.Folders;
        foreach (Folder folder in subFolders)
        {
            Items items = folder.Items;
            foreach (object item in items)
            {
                if (item is MailItem)
                {
                    MailItem mailItem = item as MailItem;
                    mailItems.Add(mailItem);
                }
            }
        }
        // Remove PST file from Default Profile
        //outlookNs.RemoveStore(rootFolder);
        return mailItems;
    }
}

}

Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78
MH731Z
  • 61
  • 11
  • Please show us the `CREATE TABLE` for the table. Is `Sender_Email`'s perhaps defined as 100 characters long? – mjwills Dec 08 '18 at 21:50
  • What is the exact value of `mailItems[i].SenderEmailAddress` (copied from the `Immediate Window`, **do not guess**) when you get a value that you don't like (like `/o=ExchangeLabs/ou=Exchange Administrative Group (FYDIBOPDLT)/cn=Recipients/cn=ed403ae50a4581-a.john`) in the database? – mjwills Dec 08 '18 at 21:51
  • `Sender_Email` longtext, - sorry not sure what you mean by "from the immediate window" the example i posted was copied from one of the fields in the database – MH731Z Dec 08 '18 at 22:15
  • https://learn.microsoft.com/en-us/visualstudio/ide/reference/immediate-window?view=vs-2017 – mjwills Dec 08 '18 at 22:19

1 Answers1

2

That is a perfectly valid address of type EX (as opposed to SMTP). You can check the sender email address type using the MailItem.SenderEmailType property. If it is SMTP, just use MailItem.SenderEmailAddress. If not, use MailItem.Sender.GetExchangeUser.PrimarySmtpAddress property (be prepared to handle errors and/or nulls). GetExchangeUser will only work if there is the original Exchange user hosting the GAL user in question in the current Outlook profile. It will not work if you only have the PST file in the profile. Chances are PidTagSenderSmtpAddress_W MAPI property (DASL name http://schemas.microsoft.com/mapi/proptag/0x5D01001F) is available on the message - you can access it using MailItem.PropertyAccessor.GetProperty - take a look at the message with OutlookSpy (I am its author - click IMessage button) to check if the property is indeed there

Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78