如何使用 OpenPop 保存电子邮件附件 [英] How to save email attachment using OpenPop

查看:59
本文介绍了如何使用 OpenPop 保存电子邮件附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a Web Email Application, How do I view and save attached files?

我正在使用 OpenPop,一个第三方 dll,我可以发送带附件的电子邮件和阅读不带附件的电子邮件.

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

这很好用:

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 save the 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 
        } 
    } 
}

推荐答案

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

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();
}

这篇关于如何使用 OpenPop 保存电子邮件附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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