使用 c# .net 库检查来自 Gmail 服务器的 IMAP 消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/545724/
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
using c# .net libraries to check for IMAP messages from gmail servers
提问by Belliez
Does anyone have any sample code in that makes use of the .Net framework that connects to googlemail servers via IMAP SSL to check for new emails?
有没有人有任何示例代码使用 .Net 框架通过 IMAP SSL 连接到 googlemail 服务器来检查新电子邮件?
采纳答案by lakshmanaraj
The URL listed here might be of interest to you
您可能对此处列出的 URL 感兴趣
http://www.codeplex.com/InterIMAP
http://www.codeplex.com/InterIMAP
which was extension to
这是扩展到
回答by Belliez
the source to the ssl version of this is here: http://atmospherian.wordpress.com/downloads/
ssl 版本的来源在这里:http: //atmospherian.wordpress.com/downloads/
回答by Jason Miesionczek
As the author of the above project i can say that yes it does support SSL.
作为上述项目的作者,我可以说是的,它确实支持 SSL。
I am currently working on a new version of the library that will be completely asynchronous to increase the speed with which it can interact with IMAP servers.
我目前正在开发一个新版本的库,该版本将完全异步以提高它与 IMAP 服务器交互的速度。
That code, while not complete, can be downloaded, along with the original synchronous library (which also supports SSL), from the code plex site linked to above.
该代码虽然不完整,但可以与原始同步库(也支持 SSL)一起从上面链接的 code plex 站点下载。
回答by Bruno Lopes
Lumisoft.nethas both IMAP client and server code that you can use.
Lumisoft.net具有您可以使用的 IMAP 客户端和服务器代码。
I've used it to download email from Gmail. The object model isn't the best, but it is workable, and seems to be rather flexible and stable.
我用它从 Gmail 下载电子邮件。对象模型不是最好的,但它是可行的,并且似乎相当灵活和稳定。
Here is the partial result of my spike to use it. It fetches the first 10 headers with envelopes, and then fetches the full message:
这是我使用它的尖峰的部分结果。它获取带有信封的前 10 个标头,然后获取完整的消息:
using (var client = new IMAP_Client())
{
client.Connect(_hostname, _port, _useSsl);
client.Authenticate(_username, _password);
client.SelectFolder("INBOX");
var sequence = new IMAP_SequenceSet();
sequence.Parse("0:10");
var fetchItems = client.FetchMessages(sequence, IMAP_FetchItem_Flags.Envelope | IMAP_FetchItlags.UID,
false, true);
foreach (var fetchItem in fetchItems)
{
Console.Out.WriteLine("message.UID = {0}", fetchItem.UID);
Console.Out.WriteLine("message.Envelope.From = {0}", fetchItem.Envelope.From);
Console.Out.WriteLine("message.Envelope.To = {0}", fetchItem.Envelope.To);
Console.Out.WriteLine("message.Envelope.Subject = {0}", fetchItem.Envelope.Subject);
Console.Out.WriteLine("message.Envelope.MessageID = {0}", fetchItem.Envelope.MessageID);
}
Console.Out.WriteLine("Fetching bodies");
foreach (var fetchItem in client.FetchMessages(sequence, IMAP_FetchItem_Flags.All, false, true)
{
var email = LumiSoft.Net.Mail.Mail_Message.ParseFromByte(fetchItem.MessageData);
Console.Out.WriteLine("email.BodyText = {0}", email.BodyText);
}
}
回答by Pawel Lesnikowski
There is no .NET framework support for IMAP. You'll need to use some 3rd party component.
IMAP 没有 .NET 框架支持。您需要使用一些 3rd 方组件。
Try Mail.dll email component, it's very affordableand easy to use, it also supports SSL:
试试Mail.dll 电子邮件组件,它非常实惠且易于使用,它还支持SSL:
using(Imap imap = new Imap())
{
imap.ConnectSSL("imap.company.com");
imap.Login("user", "password");
imap.SelectInbox();
List<long> uids = imap.Search(Flag.Unseen);
foreach (long uid in uids)
{
string eml = imap.GetMessageByUID(uid);
IMail message = new MailBuilder()
.CreateFromEml(eml);
Console.WriteLine(message.Subject);
Console.WriteLine(message.Text);
}
imap.Close(true);
}
Please note that this is a commercial product I've created.
请注意,这是我创建的商业产品。
You can download it here: https://www.limilabs.com/mail.
你可以在这里下载:https: //www.limilabs.com/mail。
回答by Pawel Lesnikowski
MailSystem.NETcontains all your need for IMAP4. It's free & open source.
MailSystem.NET包含您对 IMAP4 的所有需求。它是免费和开源的。
(I'm involved in the project)
(我参与了这个项目)
回答by wph101larrya
LumiSoft.ee - works great, fairly easy. Compiles with .NET 4.0.
LumiSoft.ee - 效果很好,相当简单。使用 .NET 4.0 编译。
Here are the required links to their lib and examples. Downloads Main:
这是指向他们的库和示例所需的链接。下载主要:
http://www.lumisoft.ee/lsWWW/Download/Downloads/
http://www.lumisoft.ee/lsWWW/Download/Downloads/
Code Examples:
代码示例:
are located here: ...lsWWW/Download/Downloads/Examples/
位于此处:...lsWWW/Download/Downloads/Examples/
.NET:
。网:
are located here: ...lsWWW/Download/Downloads/Net/
位于此处:...lsWWW/Download/Downloads/Net/
I am putting a SIMPLE sample up using their lib on codeplex (IMAPClientLumiSoft.codeplex.com). You must get their libraries directly from their site. I am not including them because I don't maintain their code nor do I have any rights to the code. Go to the links above and download it directly. I set LumiSoft project properties in my VS2010 to build all of it in .NET 4.0 which it did with no errors. Their samples are fairly complex and maybe even overly tight coding when just an example. Although I expect that these are aimed at advanced level developers in general.
我正在使用他们在 codeplex (IMAPClientLumiSoft.codeplex.com) 上的库放置一个简单的示例。您必须直接从他们的站点获取他们的库。我不包括他们,因为我不维护他们的代码,我也没有代码的任何权利。转到上面的链接并直接下载。我在我的 VS2010 中设置了 LumiSoft 项目属性,以在 .NET 4.0 中构建所有这些属性,并且没有错误。他们的样本相当复杂,甚至可能只是一个例子,编码过于紧凑。虽然我希望这些都是针对高级开发人员的。
Their project worked with minor tweaks. The tweaks: Their IMAP Client Winform example is set in the project properties as "Release" which prevents VS from breaking on debug points. You must use the solution "Configuration Manager" to set the project to "Active(Debug)" for breakpoints to work. Their examples use anonymous methods for event handlers which is great tight coding... not real good as a teaching tool. My project uses "named" event method handlers so you can set breakpoints inside the handlers. However theirs is an excellent way to handle inline code. They might have used the newer Lambda methods available since .NET 3.0 but did not and I didn't try to convert them.
他们的项目进行了细微的调整。调整:他们的 IMAP 客户端 Winform 示例在项目属性中设置为“发布”,以防止 VS 在调试点上中断。您必须使用解决方案“配置管理器”将项目设置为“活动(调试)”才能使断点工作。他们的示例对事件处理程序使用匿名方法,这是非常紧凑的编码……作为教学工具并不是很好。我的项目使用“命名”事件方法处理程序,因此您可以在处理程序内设置断点。然而,他们是处理内联代码的绝佳方式。他们可能使用了自 .NET 3.0 以来可用的较新的 Lambda 方法,但没有,我也没有尝试转换它们。
From their samples I simplified the IMAP client to bare minimum.
从他们的示例中,我将 IMAP 客户端简化到最低限度。
回答by Dominic K
Cross posted from the other similar question. See what happens when they get so similar?
Cross 从另一个类似问题发布。看看当它们变得如此相似时会发生什么?
I've been searching for an IMAP solution for a while now, and after trying quite a few, I'm going with AE.Net.Mail.
我一直在寻找 IMAP 解决方案一段时间了,在尝试了很多之后,我打算使用AE.Net.Mail。
There is no documentation, which I consider a downside, but I was able to whip this up by looking at the source code (yay for open source!) and using Intellisense. The below code connects specifically to Gmail's IMAP server:
没有文档,我认为这是一个缺点,但我能够通过查看源代码(开源的耶!)并使用 Intellisense 来提升它。以下代码专门连接到 Gmail 的 IMAP 服务器:
// Connect to the IMAP server. The 'true' parameter specifies to use SSL
// which is important (for Gmail at least)
ImapClient ic = new ImapClient("imap.gmail.com", "[email protected]", "pass",
ImapClient.AuthMethods.Login, 993, true);
// Select a mailbox. Case-insensitive
ic.SelectMailbox("INBOX");
Console.WriteLine(ic.GetMessageCount());
// Get the first *11* messages. 0 is the first message;
// and it also includes the 10th message, which is really the eleventh ;)
// MailMessage represents, well, a message in your mailbox
MailMessage[] mm = ic.GetMessages(0, 10);
foreach (MailMessage m in mm)
{
Console.WriteLine(m.Subject);
}
// Probably wiser to use a using statement
ic.Dispose();
I'm not affiliated with this library or anything, but I've found it very fast and stable.
我不隶属于这个库或任何东西,但我发现它非常快速和稳定。
回答by Kiquenet
Another alternative: HigLabo
另一种选择:HigLabo
https://higlabo.codeplex.com/documentation
https://higlabo.codeplex.com/documentation
Good discussion: https://higlabo.codeplex.com/discussions/479250
好讨论:https: //higlabo.codeplex.com/discussions/479250
//====Imap sample================================//
//You can set default value by Default property
ImapClient.Default.UserName = "your server name";
ImapClient cl = new ImapClient("your server name");
cl.UserName = "your name";
cl.Password = "pass";
cl.Ssl = false;
if (cl.Authenticate() == true)
{
Int32 MailIndex = 1;
//Get all folder
List<ImapFolder> l = cl.GetAllFolders();
ImapFolder rFolder = cl.SelectFolder("INBOX");
MailMessage mg = cl.GetMessage(MailIndex);
}
//Delete selected mail from mailbox
ImapClient pop = new ImapClient("server name", 110, "user name", "pass");
pop.AuthenticateMode = Pop3AuthenticateMode.Pop;
Int64[] DeleteIndexList = new.....//It depend on your needs
cl.DeleteEMail(DeleteIndexList);
//Get unread message list from GMail
using (ImapClient cl = new ImapClient("imap.gmail.com"))
{
cl.Port = 993;
cl.Ssl = true;
cl.UserName = "xxxxx";
cl.Password = "yyyyy";
var bl = cl.Authenticate();
if (bl == true)
{
//Select folder
ImapFolder folder = cl.SelectFolder("[Gmail]/All Mail");
//Search Unread
SearchResult list = cl.ExecuteSearch("UNSEEN UNDELETED");
//Get all unread mail
for (int i = 0; i < list.MailIndexList.Count; i++)
{
mg = cl.GetMessage(list.MailIndexList[i]);
}
}
//Change mail read state as read
cl.ExecuteStore(1, StoreItem.FlagsReplace, "UNSEEN")
}
//Create draft mail to mailbox
using (ImapClient cl = new ImapClient("imap.gmail.com"))
{
cl.Port = 993;
cl.Ssl = true;
cl.UserName = "xxxxx";
cl.Password = "yyyyy";
var bl = cl.Authenticate();
if (bl == true)
{
var smg = new SmtpMessage("from mail address", "to mail addres list"
, "cc mail address list", "This is a test mail.", "Hi.It is my draft mail");
cl.ExecuteAppend("GMail/Drafts", smg.GetDataText(), "\Draft", DateTimeOffset.Now);
}
}
//Idle
using (var cl = new ImapClient("imap.gmail.com", 993, "user name", "pass"))
{
cl.Ssl = true;
cl.ReceiveTimeout = 10 * 60 * 1000;//10 minute
if (cl.Authenticate() == true)
{
var l = cl.GetAllFolders();
ImapFolder r = cl.SelectFolder("INBOX");
//You must dispose ImapIdleCommand object
using (var cm = cl.CreateImapIdleCommand()) Caution! Ensure dispose command object
{
//This handler is invoked when you receive a mesage from server
cm.MessageReceived += (Object o, ImapIdleCommandMessageReceivedEventArgs e) =>
{
foreach (var mg in e.MessageList)
{
String text = String.Format("Type is {0} Number is {1}", mg.MessageType, mg.Number);
Console.WriteLine(text);
}
};
cl.ExecuteIdle(cm);
while (true)
{
var line = Console.ReadLine();
if (line == "done")
{
cl.ExecuteDone(cm);
break;
}
}
}
}
}
回答by jstedfast
I'd recommend looking at MailKitas it is probably the most robust mail library out there and it's Open Source (MIT).
我建议查看MailKit,因为它可能是目前最强大的邮件库,而且它是开源 (MIT)。
One of the awesome things about MailKit is that all network APIs are cancelable (something I haven't seen available in any other IMAP library).
MailKit 的一大优点是所有网络 API 都是可取消的(这是我在任何其他 IMAP 库中都没有看到的)。
It's also the only library that I know of that supports threading of messages.
它也是我所知道的唯一一个支持消息线程的库。
using System;
using System.Net;
using System.Threading;
using MailKit.Net.Imap;
using MailKit.Search;
using MailKit;
using MimeKit;
namespace TestClient {
class Program
{
public static void Main (string[] args)
{
using (var client = new ImapClient ()) {
using (var cancel = new CancellationTokenSource ()) {
client.Connect ("imap.gmail.com", 993, true, cancel.Token);
// If you want to disable an authentication mechanism,
// you can do so by removing the mechanism like this:
client.AuthenticationMechanisms.Remove ("XOAUTH");
client.Authenticate ("joey", "password", cancel.Token);
// The Inbox folder is always available...
var inbox = client.Inbox;
inbox.Open (FolderAccess.ReadOnly, cancel.Token);
Console.WriteLine ("Total messages: {0}", inbox.Count);
Console.WriteLine ("Recent messages: {0}", inbox.Recent);
// download each message based on the message index
for (int i = 0; i < inbox.Count; i++) {
var message = inbox.GetMessage (i, cancel.Token);
Console.WriteLine ("Subject: {0}", message.Subject);
}
// let's try searching for some messages...
var query = SearchQuery.DeliveredAfter (DateTime.Parse ("2013-01-12"))
.And (SearchQuery.SubjectContains ("MailKit"))
.And (SearchQuery.Seen);
foreach (var uid in inbox.Search (query, cancel.Token)) {
var message = inbox.GetMessage (uid, cancel.Token);
Console.WriteLine ("[match] {0}: {1}", uid, message.Subject);
}
client.Disconnect (true, cancel.Token);
}
}
}
}
}