IMAP IDLE模式(推送邮件)
在电子邮件技术中,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模式(推送邮件)的更多相关文章
- Quartz-第二篇 使用quartz框架定时推送邮件
1.定时推送邮件,也就是使用定时调度框架触发我们的发邮件动作,发邮件动作,请参考我的这篇随笔.
- Laravel 下结合阿里云邮件推送服务
最近在学习laravel做项目开发,遇到注册用户推送邮件的问题,之前用java做的时候是自己代码写的,也就是用ECS推送邮件,但是现在转php的laravel了就打算用php的邮件发送功能来推送邮件, ...
- PCB 后台自动系统集成与邮件推送实现
在PCB行业中,工程系统是主要数据生产者,而这些数据不仅仅给自己系统使用呀,我们需要将数据传递到各系统,才达到各系统共同协作的目的. 这里以问答方式对实现方式进行讲解.呵呵呵! 后台自动集成问题解答: ...
- Android实现推送方式解决方案 - 长连接+心跳机制(MQTT协议)
本文介绍在Android中实现推送方式的基础知识及相关解决方案.推送功能在手机开发中应用的场景是越来起来了,不说别的,就我们手机上的新闻客户端就时不j时的推送过来新的消息,很方便的阅读最新的新闻信息. ...
- Android实现推送方式解决方案(转)
本文介绍在Android中实现推送方式的基础知识及相关解决方案.推送功能在手机开发中应用的场景是越来起来了,不说别的,就我们手机上的新闻客户端就时不j时的推送过来新的消息,很方便的阅读最新的新闻信息. ...
- EDM推送
一.需求描述: 日前,做了一个发送客户账单的功能,邮件模板采用自定义,生成vm文件,保存至redis, 采用jodd-mail发送邮件,查询用户账单数据,账单明细,缓存加载模板并渲 ...
- 【转】Android实现推送方式解决方案
本文介绍在Android中实现推送方式的基础知识及相关解决方案.推送功能在手机开发中应用的场景是越来起来了,不说别的,就我们手机上的新闻客户端就时不j时的推送过来新的消息,很方便的阅读最新的新闻信息. ...
- $Django 支付宝支付,微信服务号推送消息 (测试需要把应用程序部署到服务器上)
一 支付宝支付 大概 支付宝支付 正式环境:需要用营业执照去申请商户号,appid 测试环境:沙箱环境:https://openhome.alipay.com/platform/appDaily.ht ...
- ASP.NET Core2基于RabbitMQ对Web前端实现推送功能
在我们很多的Web应用中会遇到需要从后端将指定的数据或消息实时推送到前端,通常的做法是前端写个脚本定时到后端获取,或者借助WebSocket技术实现前后端实时通讯.因定时刷新的方法弊端很多(已不再采用 ...
随机推荐
- poj 1716 Integer Intervals (差分约束 或 贪心)
Integer Intervals Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 12192 Accepted: 514 ...
- Codeforces Round #384 (Div. 2) 734E(二分答案+状态压缩DP)
题目大意 给定一个序列an,序列中只有1~8的8个整数,让你选出一个子序列,满足下列两个要求 1.不同整数出现的次数相差小于等于1 2.子序列中整数分布是连续的,即子序列的整数必须是1,1,1.... ...
- 命令__shell变量$#,$@,$0,$1,$2的含义解释
linux中shell变量$#,$@,$0,$1,$2的含义解释:变量说明:$$ Shell本身的PID(ProcessID)$! Shell最后运行的后台Process的PID$? 最后运行的命令的 ...
- DP———2.最大m子序列和
Max Sum Plus Plus Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others ...
- CENTOS6.5 安装 mysql5.6 以及搭建双主
一.Mysql5.6.10安装 1.1.必要软件 yum -y install gcc gcc-c++ autoconf automake bison ncurses-devel libtool-lt ...
- Android横竖屏总结(转)
Android横竖屏总结(转) 横竖屏切换后Activity会重新执行onCreat函数,但是在Android工程的Mainfest.xml中加入android:screenOrientation=& ...
- Windows.Forms Panel 动态加载用户控件 UserControl
创建好一个Windows Forms程序,在创建好的程序中Form1添加一个Panel控件 如图:
- Dinic算法学习&&HDU2063
http://www.cnblogs.com/SYCstudio/p/7260613.html 看这篇博文懂了一点,做题再体会体会吧 找了好久都没找到一个好用的模板…… 我也是佛了..最后决定用峰神的 ...
- go环境安装
选择想要安装的版本: http://golangtc.com/download tar -zxf go1.8.linux-amd64.tar.gz cp -R go/ /usr/local/ vi / ...
- strtol函數的用法 atof, atoi, atol, strtod, strtoul
相关函数: atof, atoi, atol, strtod, strtoul表头文件: #include <stdlib.h>定义函数: long int strtol(const ch ...