在电子邮件技术中,IDLE是RFC 2177中描述的一项IMAP功能,它允许客户端向服务器表明它已准备好接受实时通知。

Internet消息访问协议IMAP4协议,它要求客户端轮询服务器来更改所选中的文件夹(如拉取新邮件、删除邮件),如果能让服务器推送通知客户端,告知客户端有新邮件的话会更方便客户端,尤其是在手机端的时候,大量的轮询查询服务器会耗费电量和流量,用户是不太允许这样做的,而且也不是很及时的收到邮件。

考虑到这种情况,其实IMAP4的扩展协议中是支持这个推送模式,即IMAP的IDLE模式。

首先我们用CAPABILITY 命令查询一下是否支持IDLE模式,因为并不是所有邮箱多支持的。

如qq邮箱:["CAPABILITY", "IMAP4", "IMAP4rev1", "IDLE", "XAPPLEPUSHSERVICE", "AUTH=LOGIN", "NAMESPACE", "CHILDREN", "ID", "UIDPLUS"]就支持这种模式,而163邮箱:["CAPABILITY", "IMAP4rev1", "XLIST", "SPECIAL-USE", "ID", "LITERAL+", "STARTTLS", "XAPPLEPUSHSERVICE", "UIDPLUS", "X-CM-EXT-1"]并不支持。

我们就用qq邮箱来测试一下,测试前请开通QQ邮箱的imap协议功能保持连接正常,关于IDLE命令的使用,需要先登录验证后,选中文件夹之后才可以使用,具体测试如下图:

查看命令可以知道,每次收到新邮件这会更改EXISTS的数量,这样就收到一个邮件通知,然后通过这个通知在去拉取邮件就可以。这是基本原理,具体到具体应用,由于我一直使用mailkit来获取邮件,而mailkit本身也是支持这种模式的。

mailkit具体代码如下:

 namespace TestMailKit
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
TodoMail();
} public static void TodoMail()
{
try
{
using (var client = new ImapClient(new ProtocolLogger(Console.OpenStandardError())))
{
client.Connect("imap.qq.com", , true);
if (client.AuthenticationMechanisms.Contains("XOAUTH2"))
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate("110xxxxx31@qq.com", "******chfcf"); client.Inbox.Open(FolderAccess.ReadOnly); // Get the summary information of all of the messages (suitable for displaying in a message list).
var messages = client.Inbox.Fetch(, -, MessageSummaryItems.Full | MessageSummaryItems.UniqueId).ToList(); // Keep track of messages being expunged so that when the CountChanged event fires, we can tell if it's
// because new messages have arrived vs messages being removed (or some combination of the two).
client.Inbox.MessageExpunged += (sender, e) =>
{
var folder = (ImapFolder)sender; if (e.Index < messages.Count)
{
var message = messages[e.Index]; Console.WriteLine("{0}: expunged message {1}: Subject: {2}", folder, e.Index, message.Envelope.Subject); // Note: If you are keeping a local cache of message information
// (e.g. MessageSummary data) for the folder, then you'll need
// to remove the message at e.Index.
messages.RemoveAt(e.Index);
}
else
{
Console.WriteLine("{0}: expunged message {1}: Unknown message.", folder, e.Index);
}
}; // Keep track of changes to the number of messages in the folder (this is how we'll tell if new messages have arrived).
client.Inbox.CountChanged += (sender, e) =>
{
// Note: the CountChanged event will fire when new messages arrive in the folder and/or when messages are expunged.
var folder = (ImapFolder)sender; Console.WriteLine("The number of messages in {0} has changed.", folder); // Note: because we are keeping track of the MessageExpunged event and updating our
// 'messages' list, we know that if we get a CountChanged event and folder.Count is
// larger than messages.Count, then it means that new messages have arrived.
if (folder.Count > messages.Count)
{
Console.WriteLine("{0} new messages have arrived.", folder.Count - messages.Count); // Note: your first instict may be to fetch these new messages now, but you cannot do
// that in an event handler (the ImapFolder is not re-entrant).
//
// If this code had access to the 'done' CancellationTokenSource (see below), it could
// cancel that to cause the IDLE loop to end.
}
}; // Keep track of flag changes.
client.Inbox.MessageFlagsChanged += (sender, e) =>
{
var folder = (ImapFolder)sender; Console.WriteLine("{0}: flags for message {1} have changed to: {2}.", folder, e.Index, e.Flags);
}; Console.WriteLine("Hit any key to end the IDLE loop.");
using (var done = new CancellationTokenSource())
{
// Note: when the 'done' CancellationTokenSource is cancelled, it ends to IDLE loop.
var thread = new Thread(IdleLoop); thread.Start(new IdleState(client, done.Token)); Console.ReadKey();
done.Cancel();
thread.Join();
} if (client.Inbox.Count > messages.Count)
{
Console.WriteLine("The new messages that arrived during IDLE are:");
foreach (var message in client.Inbox.Fetch(messages.Count, -, MessageSummaryItems.Full | MessageSummaryItems.UniqueId))
Console.WriteLine("Subject: {0}", message.Envelope.Subject);
} client.Disconnect(true);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
} static void IdleLoop(object state)
{
var idle = (IdleState)state; lock (idle.Client.SyncRoot)
{
// Note: since the IMAP server will drop the connection after 30 minutes, we must loop sending IDLE commands that
// last ~29 minutes or until the user has requested that they do not want to IDLE anymore.
//
// For GMail, we use a 9 minute interval because they do not seem to keep the connection alive for more than ~10 minutes.
while (!idle.IsCancellationRequested)
{
// Note: Starting with .NET 4.5, you can make this simpler by using the CancellationTokenSource .ctor that
// takes a TimeSpan argument, thus eliminating the need to create a timer.
using (var timeout = new CancellationTokenSource())
{
using (var timer = new System.Timers.Timer( * * ))
{
// End the IDLE command when the timer expires.
timer.Elapsed += (sender, e) => timeout.Cancel();
timer.AutoReset = false;
timer.Enabled = true; try
{
// We set the timeout source so that if the idle.DoneToken is cancelled, it can cancel the timeout
idle.SetTimeoutSource(timeout); if (idle.Client.Capabilities.HasFlag(ImapCapabilities.Idle))
{
// The Idle() method will not return until the timeout has elapsed or idle.CancellationToken is cancelled
idle.Client.Idle(timeout.Token, idle.CancellationToken);
}
else
{
// The IMAP server does not support IDLE, so send a NOOP command instead
idle.Client.NoOp(idle.CancellationToken); // Wait for the timeout to elapse or the cancellation token to be cancelled
WaitHandle.WaitAny(new[] { timeout.Token.WaitHandle, idle.CancellationToken.WaitHandle });
}
}
catch (OperationCanceledException)
{
// This means that idle.CancellationToken was cancelled, not the DoneToken nor the timeout.
break;
}
catch (ImapProtocolException)
{
// The IMAP server sent garbage in a response and the ImapClient was unable to deal with it.
// This should never happen in practice, but it's probably still a good idea to handle it.
//
// Note: an ImapProtocolException almost always results in the ImapClient getting disconnected.
break;
}
catch (ImapCommandException)
{
// The IMAP server responded with "NO" or "BAD" to either the IDLE command or the NOOP command.
// This should never happen... but again, we're catching it for the sake of completeness.
break;
}
finally
{
// We're about to Dispose() the timeout source, so set it to null.
idle.SetTimeoutSource(null);
}
}
}
}
}
} } class IdleState
{
readonly object mutex = new object();
CancellationTokenSource timeout; /// <summary>
/// Get the cancellation token.
/// </summary>
/// <remarks>
/// <para>The cancellation token is the brute-force approach to cancelling the IDLE and/or NOOP command.</para>
/// <para>Using the cancellation token will typically drop the connection to the server and so should
/// not be used unless the client is in the process of shutting down or otherwise needs to
/// immediately abort communication with the server.</para>
/// </remarks>
/// <value>The cancellation token.</value>
public CancellationToken CancellationToken { get; private set; } /// <summary>
/// Get the done token.
/// </summary>
/// <remarks>
/// <para>The done token tells the <see cref="Program.IdleLoop"/> that the user has requested to end the loop.</para>
/// <para>When the done token is cancelled, the <see cref="Program.IdleLoop"/> will gracefully come to an end by
/// cancelling the timeout and then breaking out of the loop.</para>
/// </remarks>
/// <value>The done token.</value>
public CancellationToken DoneToken { get; private set; } /// <summary>
/// Get the IMAP client.
/// </summary>
/// <value>The IMAP client.</value>
public ImapClient Client { get; private set; } /// <summary>
/// Check whether or not either of the CancellationToken's have been cancelled.
/// </summary>
/// <value><c>true</c> if cancellation was requested; otherwise, <c>false</c>.</value>
public bool IsCancellationRequested
{
get
{
return CancellationToken.IsCancellationRequested || DoneToken.IsCancellationRequested;
}
} /// <summary>
/// Initializes a new instance of the <see cref="IdleState"/> class.
/// </summary>
/// <param name="client">The IMAP client.</param>
/// <param name="doneToken">The user-controlled 'done' token.</param>
/// <param name="cancellationToken">The brute-force cancellation token.</param>
public IdleState(ImapClient client, CancellationToken doneToken, CancellationToken cancellationToken = default(CancellationToken))
{
CancellationToken = cancellationToken;
DoneToken = doneToken;
Client = client; // When the user hits a key, end the current timeout as well
doneToken.Register(CancelTimeout);
} /// <summary>
/// Cancel the timeout token source, forcing ImapClient.Idle() to gracefully exit.
/// </summary>
void CancelTimeout()
{
lock (mutex)
{
if (timeout != null)
timeout.Cancel();
}
} /// <summary>
/// Set the timeout source.
/// </summary>
/// <param name="source">The timeout source.</param>
public void SetTimeoutSource(CancellationTokenSource source)
{
lock (mutex)
{
timeout = source; if (timeout != null && IsCancellationRequested)
timeout.Cancel();
}
}
} }

mailkit IDLE模式

通过上面的代码即可订阅邮件通知,方便的获取邮件。

IMAP IDLE模式(推送邮件)的更多相关文章

  1. Quartz-第二篇 使用quartz框架定时推送邮件

    1.定时推送邮件,也就是使用定时调度框架触发我们的发邮件动作,发邮件动作,请参考我的这篇随笔.

  2. Laravel 下结合阿里云邮件推送服务

    最近在学习laravel做项目开发,遇到注册用户推送邮件的问题,之前用java做的时候是自己代码写的,也就是用ECS推送邮件,但是现在转php的laravel了就打算用php的邮件发送功能来推送邮件, ...

  3. PCB 后台自动系统集成与邮件推送实现

    在PCB行业中,工程系统是主要数据生产者,而这些数据不仅仅给自己系统使用呀,我们需要将数据传递到各系统,才达到各系统共同协作的目的. 这里以问答方式对实现方式进行讲解.呵呵呵! 后台自动集成问题解答: ...

  4. Android实现推送方式解决方案 - 长连接+心跳机制(MQTT协议)

    本文介绍在Android中实现推送方式的基础知识及相关解决方案.推送功能在手机开发中应用的场景是越来起来了,不说别的,就我们手机上的新闻客户端就时不j时的推送过来新的消息,很方便的阅读最新的新闻信息. ...

  5. Android实现推送方式解决方案(转)

    本文介绍在Android中实现推送方式的基础知识及相关解决方案.推送功能在手机开发中应用的场景是越来起来了,不说别的,就我们手机上的新闻客户端就时不j时的推送过来新的消息,很方便的阅读最新的新闻信息. ...

  6. EDM推送

    一.需求描述:        日前,做了一个发送客户账单的功能,邮件模板采用自定义,生成vm文件,保存至redis,    采用jodd-mail发送邮件,查询用户账单数据,账单明细,缓存加载模板并渲 ...

  7. 【转】Android实现推送方式解决方案

    本文介绍在Android中实现推送方式的基础知识及相关解决方案.推送功能在手机开发中应用的场景是越来起来了,不说别的,就我们手机上的新闻客户端就时不j时的推送过来新的消息,很方便的阅读最新的新闻信息. ...

  8. $Django 支付宝支付,微信服务号推送消息 (测试需要把应用程序部署到服务器上)

    一 支付宝支付 大概 支付宝支付 正式环境:需要用营业执照去申请商户号,appid 测试环境:沙箱环境:https://openhome.alipay.com/platform/appDaily.ht ...

  9. ASP.NET Core2基于RabbitMQ对Web前端实现推送功能

    在我们很多的Web应用中会遇到需要从后端将指定的数据或消息实时推送到前端,通常的做法是前端写个脚本定时到后端获取,或者借助WebSocket技术实现前后端实时通讯.因定时刷新的方法弊端很多(已不再采用 ...

随机推荐

  1. 三十道DP练习(持续更新)(pw:DP)

    前言: 话说DP这种纯考思维的题目,总是让我很伤脑筋,一些特别简单的DP我都常常做不出来,所以革命从现在(2018-05-01)开始,努力多刷点DP的练习-. 1.顺序对齐(align) 时间:201 ...

  2. 3.6 Lucene基本检索+关键词高亮+分页

    3.2节我们已经运行了一个Lucene实现检索的小程序,这一节我们将以这个小程序为例,讲一下Lucene检索的基本步骤,同时介绍关键词高亮显示和分页返回结果这两个有用的技巧. 一.Lucene检索的基 ...

  3. spring in action 学习笔记九:如何证明在scope为prototype时每次创建的对象不同。

    spring 中scope的值有四个:分别是:singleton.prototype.session.request.其中session和request是在web应用中的. 下面证明当scope为pr ...

  4. Java基础语法实例(1)——实习第一天

    来到广州实习的第一天,我选择的是JavaEE,因为以后的方向是Java,所以就选择了它.感觉有一段时间没有接触Java了.趁此机会好好努力,将基础巩固好. Java输入及循环,判断,字符转换,数组定义 ...

  5. 物理和虚拟兼容性RDM的区别

    Difference between Physical compatibility RDMs and Virtual compatibility RDMs (2009226) Purpose This ...

  6. vue项目--favicon设置以及动态修改favicon

    最近写公司项目时,动态更新favicon 动态更新之前需要有一个默认的favicon. 目前vue-cli搭建的vue项目里面已经有了一个static文件夹,存放静态文件. favicon图片放到该文 ...

  7. c/c++: c++函数返回类型什么情况带const

    c++ 函数的返回类型,包括const 什么时候起作用呢? 函数返回值不想其立即修改的. 例子如下,这是一个简单的避免产生隐形返回变量的方法,abc 的函数返回是引用,main函数中第10行,++ 操 ...

  8. 杭电oj2064、2067、2068、2073、2076-2078、2080、2083-2085

    2064  汉诺塔III #include<stdio.h> int main(){ int n,i; _int64 s[]; while(~scanf("%d",&a ...

  9. Android平台开发-WIFI 驱动移植 -- 详细

    一.WIFI的基本架构(代码路径)     1.WIFI Settings应用程序:       packages/apps/Settings/src/com/android/settings/wif ...

  10. Fiddler抓包7-post请求(json)【转载】

    本篇转自博客:上海-悠悠 原文地址:http://www.cnblogs.com/yoyoketang/tag/fiddler/ 前言上一篇讲过get请求的参数都在url里,post的请求相对于get ...