使用POP3我们如何下载excel附件

时间:2012-12-13 05:56:49

标签: c#

以下代码适用于CSV文件但是当我们使用相同的代码来读取excel文件时,它会在文件中返回不同的字母

foreach (MimeAttachment attach in msg.Attachments)
{
if (attach.Filename != "")
{
//read data from attachment
string myString = attach.Body.Replace("=\r\n", ""); //to eliminate the '=\r\n' from email attachemnt
Byte[] b = GetBytes(myString);

// save attachment to disk
System.IO.MemoryStream mem = new System.IO.MemoryStream(b, false);
FileStream outStream = new FileStream(DownloadFilePath + "\\" + attach.Filename, FileMode.Create);
mem.WriteTo(outStream);
mem.Close();
outStream.Flush();
outStream.Close();
}
}

例如:

0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAACAAAAiwAAAAAAAAAA
EAAAjQAAAAEAAAD+////AAAAAIgAAACMAAAA////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////8J
CBAAAAYFAGcyzQfJgAEABgYAAOEAAgCwBMEAAgAAAOIAAABcAHAACQAAYXNoYWFyIE0uICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg

1 个答案:

答案 0 :(得分:1)

这对我有用

foreach (OpenPop.Mime.MessagePart attachment in attachments)
                        {
                            if (attachment != null)
                            {
                                string ext = attachment.FileName.Split('.')[1];

                                Filename = DateTime.Now.Ticks.ToString();
                                FileInfo file = new FileInfo((AppDomain.CurrentDomain.BaseDirectory + "Downloaded//") + Filename + ".csv" );

                                // Check if the file already exists
                                if (!file.Exists)
                                {
                                    attachment.Save(file);
                                }

                            }
                  }

或试试这个

How to save email attachments in C#