Getting infos from Mail body via Regex

Hey guys,

I have a mail with the the body described below. I want to read the content line by line to different variables via Regex:

mailbody:

From: hello@mail.com hello@mail.com
Send: Monday, 31. January 2022, 16:33
To: bye@mail.com bye@mail.com
Subject: This is a Subject

And then below here is some other content
bla bla

I want:
str_from = “hello@mail.com
str_to = “bye@mail.com
str_subject = “This is a Subject”

So basically it always starts with the word and then i need to read the line til end :slight_smile:

Thanks for your help!

Hi @Pathler

Use Assign activity
LHS - Create an Variable
RHS - System.Text.RegularExpression.Regex.match(“Input String”,“(?<=From:\s)\S+|(?<=To:\s)\S+|(?<=Subject:\s)\S.+”).Tostring

Hope it works

Regards
Gokul

Hi,

If you open to all options(other than Regex), you can give read the entire body as a string and split it by Environment.NewLine The result would an array of string. It would look something like -
[EmailBodyString].Split({Environment.NewLine},StringSplitOptions.None)

If you encounter an empty array item, it means you have encountered an empty line. In the example you had shared, you would be needing the first 4 array items from the result. This is especially useful when you have to extract “From”, “Send”, “To” and “Subject” values

1 Like

@mbalaji1985 , great idea. thanks! What is the best way to assign the variables afterwards without using a for each loop for every single variable? :slight_smile:

You can use LINQ or Lambda query. Lambda query would be like -
[ArrayOfString].AsEnumerable().Where(Function(w) w.Contains(“Subject”))(0)

Hi,

We can extract each value using the following expression. Can you try this?

First, set target keywords to string array variable in advance.

keywords = {"From","To","Subject"}

Then the following expression returns Dictionary<string,string> type variable. We can get each value like dict("Subject")

dict = keywords.ToDictionary(Function(s) s,Function(s) System.Text.RegularExpressions.Regex.Match(mailBody,"(?<=^"+System.Text.RegularExpressions.Regex.Escape(s)+":\s*).*",System.Text.RegularExpressions.RegexOptions.Multiline).Value)

Sample20220201-1.zip (13.1 KB)

Hope this helps you.

Regards,