我正在使用OpenPop.net尝试解析来自给定收件箱中所有电子邮件的链接。我找到了这个方法来获取所有信息:
public static List<OpenPop.Mime.Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
{
// The client disconnects from the server when being disposed
using (Pop3Client client = new Pop3Client())
{
// Connect to the server
client.Connect(hostname, port, useSsl);
// Authenticate ourselves towards the server
client.Authenticate(username, password);
// Get the number of messages in the inbox
int messageCount = client.GetMessageCount();
// We want to download all messages
List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount);
// Messages are numbered in the interval: [1, messageCount]
// Ergo: message numbers are 1-based.
// Most servers give the latest message the highest number
for (int i = messageCount; i > 0; i--)
{
allMessages.Add(client.GetMessage(i));
}
client.Disconnect();
// Now return the fetched messages
return allMessages;
}
}
现在我正在尝试遍历每条消息,但我似乎无法弄清楚如何做到这一点,到目前为止我的按钮已经有了这个:
private void button7_Click(object sender, EventArgs e)
{
List<OpenPop.Mime.Message> allaEmail = FetchAllMessages("pop3.live.com", 995, true, "xxxxx@hotmail.com", "xxxxx");
var message = string.Join(",", allaEmail);
MessageBox.Show(message);
}
我如何遍历allaEmail中的每个条目,以便我可以在MessageBox中显示它?
答案 0 :(得分:28)
我可以看到您使用OpenPop主页中的fetchAllEmail example。类似的示例showing how to get body text也在主页上。
您可能还想了解电子邮件的实际结构。为此目的存在email introduction。
说完了,我会做类似下面代码的事情。
private void button7_Click(object sender, EventArgs e)
{
List<OpenPop.Mime.Message> allaEmail = FetchAllMessages(...);
StringBuilder builder = new StringBuilder();
foreach(OpenPop.Mime.Message message in allaEmail)
{
OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();
if(plainText != null)
{
// We found some plaintext!
builder.Append(plainText.GetBodyAsText());
} else
{
// Might include a part holding html instead
OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion();
if(html != null)
{
// We found some html!
builder.Append(html.GetBodyAsText());
}
}
}
MessageBox.Show(builder.ToString());
}
我希望这可以帮助你。请注意,OpenPop还有online documentation。
答案 1 :(得分:0)
我就这样做了:
string Body = msgList[0].MessagePart.MessageParts[0].GetBodyAsText();
foreach( string d in Body.Split('\n')){
Console.WriteLine(d);
}
希望它有所帮助。
答案 2 :(得分:0)
此问题中的其他答案不完整且不正确,主要是因为它们从未使用过至关重要的FindAllTextVersions
方法。
这是获取实际正文内容的完整方法:
private static string GetMessageBodyAsText(Message message)
{
try
{
List<MessagePart> list = message.FindAllTextVersions();
// First let's try getting the plain text part:
foreach (MessagePart part in list)
{
if (part != null)
{
return part.GetBodyAsText();
}
}
// Now let's try getting the HTML part
MessagePart html = message.FindFirstHtmlVersion();
if (html != null)
{
return html.GetBodyAsText();
}
return null;
}
catch (Exception exc)
{
// Handle your exception here
return null;
}
}