如何将exctrected email插入到C#中的csv文件中? [英] how to exctrected email insert into csv file in C#?

查看:75
本文介绍了如何将exctrected email插入到C#中的csv文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 使用系统; 
使用 System.Collections.Generic;
使用 System.ComponentModel;
使用 System.Data;
使用 System.Drawing;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;
使用 System.Windows.Forms;
使用 System.IO;
使用 System.Text.RegularExpressions;
使用 Excel = Microsoft.Office.Interop.Excel;
使用 word = Microsoft.Office.Interop.Word;

命名空间 E_mailExtractor
{
public partial class Form1:Form
{
public Form1()
{
InitializeComponent();
}

private void btnText_Click( object sender,EventArgs e)
{
string path = Application.StartupPath + @ \\E-mail-Text.txt;
TextWriter tw = new StreamWriter(path);
tw.Close();
// 否则if(File.Exists(path))
// {
// < span class =code-comment> TextWriter tw = new StreamWriter(path);
// tw.WriteLine(下一行!);
// tw。关();
// }
// StreamWriter tw11 = new StreamWriter(j.txt);
// tw11.WriteLine(hiiiiiiiiii);
// < span class =code-comment> char ch;
// int Tchar = 0 ;
// int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // 显示对话框。
if (result == DialogResult.OK) // 测试结果。
{
string file = openFileDialog1.FileName;
尝试
{
string text = File.ReadAllText(file );
// size = text.Length;
// MessageBox.Show(file.ToString());
/ / label1.Text = text;
// StreamReader reader = new StreamReader(file);
// do
// {
// ch =(char)reader.Read();
// //label2.Text = ch.ToString();
// if(Convert.ToInt32(ch)== 34)
/ / {
// Console.Write(@;);
// }
// Tchar ++;
/ / } while(!reader.EndOfStream);

const string MatchEmailPattern =
@ (( [\w - ] + \)+ [\w - ] + |。([A-ZA-Z] {1} | [\w - ] {2,}))@
+ @ (([0-1] ?[0-9] {1,2} | 25 [0-5] | 2 [0-4] [0-9])\([0-1] [0-9] {1,2。? } | 25 [0-5] | 2 [0-4] [0-9])\。
+ @ ([0-1]?[0-9] {1,2} | 25 [0-5] | 2 [0-4] [0-9])\。 ([0-1]?[0-9] {1,2} | 25 [0-5] | 2 [0-4] [0-9])){1} |
+ @ ([a-zA-Z] + [\w - ] + \。)+ [一个-ZA-Z] {2,4});
Regex rx = new 正则表达式(MatchEmailPattern,RegexOptions.Compiled | RegexOptions.IgnoreCase);
// 查找匹配项。
MatchCollection matches = rx.Matches(text) ;
// 报告找到的匹配数。
int noOfMatches = matches.Count;
MessageBox.Show( E-mail Found = + noOfMatches);
// 每场比赛的报告。
FileStream fs1 = new FileStream(path,FileMode.OpenOrCreate,FileAccess.Write);
StreamWriter writer = new StreamWriter(fs1);
foreach (匹配匹配 匹配)
{
string s = match.ToString();
writer.WriteLine(match.ToString()+ );
}
writer.Close();

string sourceFilePath = path;
string destinationFilePath = path;
var readLines = File.ReadAllLines(sourceFilePath,Encoding.Default);
File.WriteAllLines(destinationFilePath,readLines.Distinct()。ToArray(),Encoding.Default);
}
catch (Exception ex)
{
MessageBox.Show( + ex);
}
}
MessageBox.Show( 成功提取电子邮件< /跨度>); // < - 在调试模式下显示文件大小。
// < - 供调试使用。
}

private void Form1_Load( object sender,EventArgs e)
{
// StreamWriter writer =
// new StreamWriter(D:\\\\\ _dxt,true);

// writer.WriteLine(重要数据行1);

// //将行添加到文件中。
// StreamWriter writer1 =
// new StreamWriter(D:\\\\ my.txt,true);

// writer1.WriteLine(Line 2);



}

private void btnExcel_Click( object sender,EventArgs e)
{
string path = Application.StartupPath + @ \\E-mail-Excel.txt;
TextWriter tw = new StreamWriter(path);
tw.Close();
DialogResult result = openFileDialog2.ShowDialog();
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range范围;

string str;
int rCnt = 0 ;
int cCnt = 0 ;

if (result == DialogResult.OK) // 测试结果。
{
string file = openFileDialog2.FileName;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(文件, 0 true 5 true ,Microsoft.Office.Interop.Excel.XlPlatform。 xlWindows, \t false false 0 true 1 0 );
xlWorkSheet =(Excel.Worksheet)xlWorkBook.Worksheets.get_Item( 1 );
range = xlWorkSheet.UsedRange;

FileStream fs1 = new FileStream(path,FileMode.OpenOrCreate,FileAccess.Write);
StreamWriter writer = new StreamWriter(fs1);

for (rCnt = 1 ; rCnt < = range.Rows.Count; rCnt ++)
{
for (cCnt = 1 ; cCnt < = range.Columns.Count; cCnt ++)
{
const string MatchEmailPattern =
@ (([\w - ] + \)+ [\w - ] + |。([A-ZA-Z] {1} | [\w - ] {2- ,}))@

+ @ (([0-1]? [0-9] {1,2} | 25 [0-5] |。?2 [0-4] [0-9])\([0-1] [0-9] {1,2} | 25 [0-5] | 2 [0-4] [0-9])\。
+ @ < span class =code-string>([0-1]?[0-9] {1,2} | 25 [0-5] | 2 [0-4] [0-9])\。( [0-1] [0-9 ] {1,2} | 25 [0-5] | 2 [0-4] [0-9])){1} |

+ @ ([a-zA-Z] + [\w - ] + \。)+ [a-zA-Z] {2,4} );
str =( string )(range.Cells [rCnt,cCnt] as Excel.Range ).Value2;
if (str!= null
{
Regex rx = new 正则表达式(MatchEmailPattern,RegexOptions.Compiled | RegexOptions.IgnoreCase);
// 查找匹配项。
MatchCollection matches = rx.Matches(str) ;
// int noOfMatches = matches.Count;
// MessageBox.Show(发现电子邮件+ cCnt +行+ noOfMatches);
foreach (匹配匹配 匹配)
{
// MessageBox.Show(match.ToString());
writer.WriteLine(match.ToString()+ < span class =code-string>
);
}
}
}

}

writer.Close();
string sourceFilePath = path;
string destinationFilePath = path;
var readLines = File.ReadAllLines(sourceFilePath,Encoding.Default);
File.WriteAllLines(destinationFilePath,readLines.Distinct()。ToArray(),Encoding.Default);
xlWorkBook.Close( true null );
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show( 成功提取电子邮件);
}
}

private void releaseObject( object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(OBJ);
obj = null ;
}
catch (例外情况)
{
obj = null ;
MessageBox.Show( 无法释放对象 + ex.ToString()) ;
}
最后
{
GC.Collect();
}
}

private void btnWord_Click( object sender,EventArgs e)
{
string path = Application.StartupPath + @ \\E-mail-Word.txt;
TextWriter tw = new StreamWriter(path);
tw.Close();
DialogResult result = openFileDialog3.ShowDialog();
if (result == DialogResult.OK) // 测试结果。
{
string file = openFileDialog3.FileName;
尝试
{

// 打开一个doc文件。
word.Document document;
word.Application application;
application = new word.Application();
document = application.Documents.Open(file);

// 遍历文档中的所有单词。
int count = document.Words.Count;
for int i = 1 ; i < = count; i ++)
{
// 写下单词。
string str = document.Words [i] .Text;

}
document.ActiveWindow.Selection.WholeStory();

document.ActiveWindow.Selection.Copy();

IDataObject data = Clipboard.GetDataObject();

string text = data.GetData(DataFormats.Text).ToString();

const string MatchEmailPattern =
@ (([\\\ - ] + \。)+ [\w - ] + |([a-zA-Z] {1} | [\w - ] {2,}))@
+ @ ((([0-1] [0-9] {1,2} |?25 [0-5] | 2 [0-4] [0-9])\([0-1。 ]?[0-9] {1,2} | 25 [0-5] | 2 [0-4] [0-9])\。
+ @ ([0-1]?[0-9] {1,2} | 25 [0-5] | 2 [0- 4] [0-9])\([0-1] [0-9] {1,2} |。?25 [0-5] | 2 [0-4] [0-9])){ 1} |
+ @ ([a-zA-Z] + [\\ \\w - ] + \)+ [A-ZA-Z] {2,4})
Regex rx = new 正则表达式(MatchEmailPattern,RegexOptions.Compiled | RegexOptions.IgnoreCase);
// 查找匹配项。
MatchCollection matches = rx.Matches(text) ;
// 报告找到的匹配数。
int noOfMatches = matches.Count;
MessageBox.Show( E-mail Found = + noOfMatches);
// 每场比赛的报告。
FileStream fs1 = new FileStream(path,FileMode.OpenOrCreate,FileAccess.Write);
StreamWriter writer = new StreamWriter(fs1);
foreach (匹配匹配 匹配)
{
string s = match.ToString();
writer.WriteLine(match.ToString()+ );
}
writer.Close();

string sourceFilePath = path;
string destinationFilePath = path;
var readLines = File.ReadAllLines(sourceFilePath,Encoding.Default);
File.WriteAllLines(destinationFilePath,readLines.Distinct()。ToArray(),Encoding.Default);
document.Close();
application.Quit();

}
catch (例外情况)
{
MessageBox.Show( + ex);
}
}
// 关闭字。
MessageBox.Show( 成功提取电子邮件);


}
}
}

解决方案

这不是一个问题。然而,一个可用的开源库可以帮助您解决几乎所有的电子邮件提取问题,OpenPop.NET: http ://sourceforge.net/projects/hpop [ ^ ] 。



不要混淆:看起来这个库可能与POP3协议有关,但事实并非如此。是的,可以使用客户端POP3协议实现,但这不是最重要的部分。该项目可用作有关MIME类型,格式,以及全面解析电子邮件所需的所有内容的各种标准/ RFC的详细参考。



-SA


实际上有什么问题?网上有很多开源电子邮件提取器,您可以轻松使用它。

电子邮件提取器 [ ^ ]



http://emailgrabber.codeplex.com/ [ ^ ]



等等......

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using Excel = Microsoft.Office.Interop.Excel;
using word = Microsoft.Office.Interop.Word;

namespace E_mailExtractor
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnText_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + @"\\E-mail-Text.txt";
            TextWriter tw = new StreamWriter(path);
            tw.Close();
            //else if (File.Exists(path))
            //    {
            //   TextWriter tw = new StreamWriter(path);
            //   tw.WriteLine("The next line!");
            //   tw.Close(); 
            //            }
            //StreamWriter tw11 = new StreamWriter("j.txt");
            //tw11.WriteLine("hiiiiiiiiii");
            //char ch;
            //int Tchar = 0;
            //int size = -1;
            DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
            if (result == DialogResult.OK) // Test result.
            {
                string file = openFileDialog1.FileName;
                try
                {
                    string text = File.ReadAllText(file);
                    //size = text.Length;
                    // MessageBox.Show(file.ToString());
                    //label1.Text = text;
                    //StreamReader reader = new StreamReader(file);
                    //do
                    //{
                    //    ch = (char)reader.Read();
                    //    //label2.Text = ch.ToString();
                    //    if (Convert.ToInt32(ch) == 34)
                    //    {
                    //        Console.Write(@";");
                    //    }
                    //    Tchar++;
                    //} while (!reader.EndOfStream);

                    const string MatchEmailPattern =
      @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
      + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
        + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
      + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";
                    Regex rx = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    // Find matches.
                    MatchCollection matches = rx.Matches(text);
                    // Report the number of matches found.
                    int noOfMatches = matches.Count;
                    MessageBox.Show("E-mail Found ="+noOfMatches);
                    // Report on each match.
                    FileStream fs1 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
                    StreamWriter writer = new StreamWriter(fs1);
                    foreach (Match match in matches)
                    {
                        string s = match.ToString();
                        writer.WriteLine(match.ToString() + ",");
                    }
                    writer.Close();

                    string sourceFilePath = path;
                    string destinationFilePath = path;
                    var readLines = File.ReadAllLines(sourceFilePath, Encoding.Default);
                    File.WriteAllLines(destinationFilePath, readLines.Distinct().ToArray(), Encoding.Default);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("" + ex);
                }
            }
            MessageBox.Show("Successfully Extract E-mail"); // <-- Shows file size in debugging mode.
            //<-- For debugging use.
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //        StreamWriter writer =
            //             new StreamWriter("D:\\j.txt", true);

            //            writer.WriteLine("Important data line 1");

            //        // Append line to the file.
            //StreamWriter writer1 =
            //            new StreamWriter("D:\\j.txt", true);

            //            writer1.WriteLine("Line 2");



        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + @"\\E-mail-Excel.txt";
            TextWriter tw = new StreamWriter(path);
            tw.Close();
            DialogResult result = openFileDialog2.ShowDialog();
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            Excel.Range range;

            string str;
            int rCnt = 0;
            int cCnt = 0;

            if (result == DialogResult.OK) // Test result.
            {
                string file = openFileDialog2.FileName;
                xlApp = new Excel.Application();
                xlWorkBook = xlApp.Workbooks.Open(file, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                range = xlWorkSheet.UsedRange;

                FileStream fs1 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter writer = new StreamWriter(fs1);

                for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
                {
                    for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
                    {
                        const string MatchEmailPattern =
         @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
         + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
           + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
         + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";
                        str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
                        if (str != null)
                        {
                            Regex rx = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                            // Find matches.
                            MatchCollection matches = rx.Matches(str);
                            //int noOfMatches = matches.Count;
                            //MessageBox.Show("E-mail Found In " + cCnt +"Row" + noOfMatches);
                            foreach (Match match in matches)
                            {
                                //MessageBox.Show(match.ToString());
                                writer.WriteLine(match.ToString() + ",");
                            }
                        }
                    }

                }

                writer.Close();
                string sourceFilePath = path;
                string destinationFilePath = path;
                var readLines = File.ReadAllLines(sourceFilePath, Encoding.Default);
                File.WriteAllLines(destinationFilePath, readLines.Distinct().ToArray(), Encoding.Default);
                xlWorkBook.Close(true, null, null);
                xlApp.Quit();

                releaseObject(xlWorkSheet);
                releaseObject(xlWorkBook);
                releaseObject(xlApp);
                MessageBox.Show("Successfully Extract E-mail");
            }
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

        private void btnWord_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + @"\\E-mail-Word.txt";
            TextWriter tw = new StreamWriter(path);
            tw.Close();
            DialogResult result = openFileDialog3.ShowDialog();
            if (result == DialogResult.OK) // Test result.
            {
                string file = openFileDialog3.FileName;
                try
                {
                    
                    // Open a doc file.
                    word.Document document;
                    word.Application application;
                    application = new word.Application();
                    document = application.Documents.Open(file);
                    
                    // Loop through all words in the document.
                    int count = document.Words.Count;
                    for (int i = 1; i <= count; i++)
                    {
                        // Write the word.
                        string str = document.Words[i].Text;
                    
                    }
                    document.ActiveWindow.Selection.WholeStory();

                    document.ActiveWindow.Selection.Copy();

                    IDataObject data = Clipboard.GetDataObject();

                    string text = data.GetData(DataFormats.Text).ToString();

                    const string MatchEmailPattern =
     @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
     + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
       + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
     + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";
                    Regex rx = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    // Find matches.
                    MatchCollection matches = rx.Matches(text);
                    // Report the number of matches found.
                    int noOfMatches = matches.Count;
                    MessageBox.Show("E-mail Found =" + noOfMatches);
                    // Report on each match.
                    FileStream fs1 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
                    StreamWriter writer = new StreamWriter(fs1);
                    foreach (Match match in matches)
                    {
                        string s = match.ToString();
                        writer.WriteLine(match.ToString() + ",");
                    }
                    writer.Close();

                    string sourceFilePath = path;
                    string destinationFilePath = path;
                    var readLines = File.ReadAllLines(sourceFilePath, Encoding.Default);
                    File.WriteAllLines(destinationFilePath, readLines.Distinct().ToArray(), Encoding.Default);
                    document.Close();
                    application.Quit();
                  
                }
                catch (Exception ex)
                {
                    MessageBox.Show("" + ex);
                }
            }
            // Close word.
            MessageBox.Show("Successfully Extract E-mail");
           

        }
    }
}

解决方案

This is not a question at all. Nevertheless, one of the available open-source libraries which can help you with nearly all of your "e-mail extraction" problems is OpenPop.NET: http://sourceforge.net/projects/hpop[^].

Don't be confused: it may seem that the library is about POP3 protocol, this is not so. Yes, client-side POP3 protocol implementation is available, but this is not the most important part of it. The project can be used as a detailed references on all kinds of standards/RFCs on MIME types, formats, everything which is needed for comprehensive parsing of an e-mail message.

—SA


What is the Questions actually? There are many open source email extractor available at web you can use it easily.
Emails Extractor[^]

http://emailgrabber.codeplex.com/[^]

and many more...


这篇关于如何将exctrected email插入到C#中的csv文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆