Extract the EmailID from the Text File

Posted by Venkat | Labels: ,

Here is the another article ie: which is going to find the emailID on the Text File and assign to a string.

Here i have the Textfile ie: Notepad File on the Server folder.

in the notepad file i have some content and emailID too, so i want to get the EmailID from the file so i have to send email to that user.

For this i am using REGEX so its easy to find the emailID on the text file and add or store it on arrays.

Here i am using the Two Method both are using REGEX pattern.


Here you go.. I tested - its working fine.

First Method:

using System.Text.RegularExpressions;
using System.IO;

try
{
//the file is in the root - you may need to change it
string filePath = MapPath("~") + "/EmailText.txt";

using (StreamReader sr = new StreamReader( filePath) )
{
string content = sr.ReadToEnd();
if (content.Length > 0)
{
//this pattern is taken from Asp.Net regular expression validators library
string pattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
MatchCollection mc = Regex.Matches(content, pattern);
for (int i = 0; i < mc.Count; i++)
{
//here am just printing it.. You can send mails to mc[i].Value in thsi loop
Response.Write(mc[i].Value + "
");
}
}
}
}
catch (Exception ee)
{
Response.Write(ee.Message);
}

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Second Method:

string pattern = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";

System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pattern);

//Read file
string sFileContents =System.IO.File.ReadAllText(Server.MapPath("Email.txt"));

System.Text.RegularExpressions.MatchCollection mc = reg.Matches(sFileContents);

//string array for stroing
System.Collections.Generic.List str = new System.Collections.Generic.List();foreach (System.Text.RegularExpressions.Match m in mc)

{

str.Add(m.Value);

}

OUTPUT

input file
----------

jeevan@test.com This e-mail address is being protected from spambots. You need JavaScript enabled to view it ,

Welcome yo Hyderabadtechies.info
test@test.com This e-mail address is being protected from spambots. You need JavaScript enabled to view it ,
its really cool....

Chandrasekarthotta@gmail.com This e-mail address is being protected from spambots. You need JavaScript enabled to view it

sdf

sdfs

dfsd



output :


jeevan@test.com This e-mail address is being protected from spambots. You need JavaScript enabled to view it , test@test.com This e-mail address is being protected from spambots. You need JavaScript enabled to view it , Chandrasekarthotta@gmail.com

PayOffers.in