Gonzo345
Gonzo345

Reputation: 1333

Mailkit: Could I get the original sender from a forwarded e-mail?

I'm managing forwarded e-mails and noting that if I perform a TextSearchQuery(SearchTerm.FromContains, "test@test.com") I just get the UniqueIds of the forwarder, not the original sender of the e-mail.

I know I could dive into the TextBody or the HtmlBody and look at the "from", but this could vary depending on the language of the client and so on, so I was wondering if is there any method to perform that "deep SearchQuery".

There are so many SearchTerm but a SearchTerm.OriginalFromContains could be interesting, if it doesn't exists yet!

Thanks.

Upvotes: 0

Views: 1352

Answers (3)

Szynkie
Szynkie

Reputation: 79

Previous answers are ok, but none of them will give us senders. Same as @Gonzo345 in last answer we can find emails in message.HtmlBody. My solution:

string afterFromPattern = @"From:.*(\n|\r|\r\n)";
string emailPattern = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
foreach (Match match in Regex.Matches(message.HtmlBody, afterFromPattern))
{
   fromEmail = Regex.Match(match.Value, emailPattern).Value.ToLower();
   if (string.IsNullOrEmpty(fromEmail))
   {
      continue;
   }

   fromEmails.Add(fromEmail);                              
}

Upvotes: 0

Gonzo345
Gonzo345

Reputation: 1333

It's not a fire-proof solution but I actually search for all the "mailTo"s on the e-mail, I list them and I give the user the option to exclude a concrete domain of the list.

I finally pick up the last mailTo.

private string ExtractMailTo(string html, string domainToExclude)
{
    try
    {   //Searches for mailTos with regEx
        //If user didn't pass any domain we will just ignore it
        //and pick up the last mailTo.
        bool deleteDomainUser = (!string.IsNullOrEmpty(domainToExclude)
            || !string.IsNullOrWhiteSpace(domainToExclude));

        var mailTos = new List<String>();
        string pattern = @"mailto\s*:\s*([^""'>]*)";
        foreach (Match match in Regex.Matches(html, pattern))
            mailTos.Add(match.Groups[1].Value);

        if(deleteDomainUser)
            //We search for the domain concreted by the user
            //and we delete it from the mailTos List
            mailTos.RemoveAll(doms => doms.Contains(domainToExclude));
        var last = mailTos.Last();
        return last;
    }
    catch (Exception ex)
    {
        string message = "A problem ocurred parsing the e-mail body searching for MailTos. \n" 
                + ex.Message;
        throw new Exception(message, ex);
    }
}

Hope it helps somebody.

Upvotes: 2

jstedfast
jstedfast

Reputation: 38618

There's no way to do what you want as IMAP does not support it. MailKit's search API's are limited to the search capabilities of the IMAP protocol (which, unfortunately, are rather limited).

Upvotes: 1

Related Questions