C# 如何使用 OpenPop 保存电子邮件附件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10317411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:20:50  来源:igfitidea点击:

How to save email attachment using OpenPop

c#emailsaveattachmentopenpop

提问by Pomster

I have created a Web Email Application, How do I viewand saveattached files?

我创建了一个 Web 电子邮件应用程序,如何查看保存附件?

I am using OpenPop, a third Party dll, I can send emails with attachments and read emails with no attachments.

我正在使用OpenPop,一个第三方 dll,我可以发送带有附件的电子邮件并阅读没有附件的电子邮件。

This works fine:

这工作正常:

Pop3Client pop3Client = (Pop3Client)Session["Pop3Client"]; // Creating newPopClient 
int messageNumber = int.Parse(Request.QueryString["MessageNumber"]);
Message message = pop3Client.GetMessage(messageNumber);
MessagePart messagePart = message.MessagePart.MessageParts[1];
lblFrom.Text = message.Headers.From.Address; // Writeing message. 
lblSubject.Text = message.Headers.Subject;
lblBody.Text=messagePart.BodyEncoding.GetString(messagePart.Body);

This second portion of code displays the contents of the attachment, but that's only useful if its a text file. I need to be able to savethe attachment. Also the bottom section of code I have here over writes the body of my message, so if I receive an attachment I can't view my message body.

代码的第二部分显示附件的内容,但只有在它是文本文件时才有用。我需要能够保存附件。此外,我在这里的代码的底部部分覆盖了我的消息正文,因此如果我收到附件,我将无法查看我的消息正文。

if (messagePart.IsAttachment == true) { 
    foreach (MessagePart attachment in message.FindAllAttachments()) { 
        if (attachment.FileName.Equals("blabla.pdf")) { // Save the raw bytes to a file
            File.WriteAllBytes(attachment.FileName, attachment.Body); //overwrites MessagePart.Body with attachment 
        } 
    } 
}

回答by Stanislav Berkov

The OpenPop.Mime.Messageclass has ToMailMessage()method that converts OpenPop's Message to System.Net.Mail.MailMessage, which has an Attachmentsproperty. Try extracting attachments from there.

OpenPop.Mime.Message该类具有ToMailMessage()将 OpenPop 的 Message 转换为 的方法,该方法System.Net.Mail.MailMessage具有一个Attachments属性。尝试从那里提取附件。

回答by Karl

I wrote this quite a long time ago, but have a look at this block of code that I used for saving XML attachments within email messages sat on a POP server:

我很久以前写过这个,但是看看我用来在 POP 服务器上的电子邮件消息中保存 XML 附件的代码块:

OpenPOP.POP3.POPClient client = new POPClient("pop.yourserver.co.uk", 110, "[email protected]", "password_goes_here", AuthenticationMethod.USERPASS); 
if (client.Connected) {
int msgCount = client.GetMessageCount();

/* Cycle through messages */
for (int x = 0; x < msgCount; x++)
    {
        OpenPOP.MIMEParser.Message msg = client.GetMessage(x, false);
        if (msg != null) {
            for (int y = 0; y < msg.AttachmentCount; y++)
            {
                Attachment attachment = (Attachment)msg.Attachments[y];

                if (string.Compare(attachment.ContentType, "text/xml") == 0)
                {
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

                    string xml = attachment.DecodeAsText();
                    doc.LoadXml(xml);
                    doc.Save(@"C:\POP3Temp\test.xml");
                }
            }
        }
    }
}

回答by adopilot

for future readers there is easier way with newer releases of Pop3

对于未来的读者,使用较新版本的 Pop3 有更简单的方法

using( OpenPop.Pop3.Pop3Client client = new Pop3Client())
        {
            client.Connect("in.mail.Your.Mailserver.com", 110, false);
            client.Authenticate("usernamePop3", "passwordPop3", AuthenticationMethod.UsernameAndPassword);
            if (client.Connected)
            {
                int messageCount = client.GetMessageCount();
                List<Message> allMessages = new List<Message>(messageCount);
                for (int i = messageCount; i > 0; i--)
                {
                    allMessages.Add(client.GetMessage(i));
                }
                foreach (Message msg in allMessages)
                {
                    var att = msg.FindAllAttachments();
                    foreach (var ado in att)
                    {
                        ado.Save(new System.IO.FileInfo(System.IO.Path.Combine("c:\xlsx", ado.FileName)));
                    }
                }
            }
           }

回答by ElectricRouge

If anyone is still looking for answer this worked fine for me.

如果有人仍在寻找答案,这对我来说很好。

var client = new Pop3Client();
try
{            
    client.Connect("MailServerName", Port_Number, UseSSL); //UseSSL true or false
    client.Authenticate("UserID", "password");   

    var messageCount = client.GetMessageCount();
    var Messages = new List<Message>(messageCount);

    for (int i = 0;i < messageCount; i++)
    {
        Message getMessage = client.GetMessage(i + 1);
        Messages.Add(getMessage);
    }

    foreach (Message msg in Messages)
    {
        foreach (var attachment in msg.FindAllAttachments())
        {
            string filePath = Path.Combine(@"C:\Attachment", attachment.FileName);
            if(attachment.FileName.Equals("blabla.pdf"))
            {
                FileStream Stream = new FileStream(filePath, FileMode.Create);
                BinaryWriter BinaryStream = new BinaryWriter(Stream);
                BinaryStream.Write(attachment.Body);
                BinaryStream.Close();
            }
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine("", ex.Message);
}
finally
{
    if (client.Connected)
        client.Dispose();
}

回答by Dieter Stalmann

Just in case someone wants the code for VB.NET:

以防万一有人想要 VB.NET 的代码:

For Each emailAttachment In client.GetMessage(count).FindAllAttachments
    AttachmentName = emailAttachment.FileName
    '----// Write the file to the folder in the following format: <UniqueID> followed by two underscores followed by the <AttachmentName>
    Dim strmFile As New FileStream(Path.Combine("C:\Test\Attachments", EmailUniqueID & "__" & AttachmentName), FileMode.Create)
    Dim BinaryStream = New BinaryWriter(strmFile)
    BinaryStream.Write(emailAttachment.Body)
    BinaryStream.Close()
Next

回答by VAMSHI PAIDIMARRI

 List<Message> lstMessages = FetchAllMessages("pop.mail-server.com", 995, true,"Your Email ID", "Your Password");

The above line of code gets the list of all the messages from your email using corresponding pop mail-server.

上面的代码行使用相应的 pop 邮件服务器从您的电子邮件中获取所有消息的列表。

For example, to get the attachment of latest (or first) email in the list, you can write following piece of code.

例如,要获取列表中最新(或第一封)电子邮件的附件,您可以编写以下代码。

 List<MessagePart> lstAttachments = lstMessages[0].FindAllAttachments();  //Gets all the attachments associated with latest (or first) email from the list.
 for (int attachment = 0; attachment < lstAttachments.Count; attachment++)
 {
         FileInfo file = new FileInfo("Some File Name");
         lstAttachments[attachment].Save(file);
 } 

回答by Bruno Jares

    private KeyValuePair<byte[], FileInfo> parse(MessagePart part)
    {
        var _steam = new MemoryStream();
        part.Save(_steam);
        //...
        var _info = new FileInfo(part.FileName);
        return new KeyValuePair<byte[], FileInfo>(_steam.ToArray(), _info);
    }

    //... How to use
    var _attachments = message 
        .FindAllAttachments()
        .Select(a => parse(a))
    ;