(对不住大家了,这几天公司项目太忙,加上身体不适,有几天没有来更新了。)
我们需要做两个 WebService,一个用来接收邮件,一个用来发送邮件:
- Receiver.asmx
- Sender.asmx
然后在 WebService 中各添加一个方法 Start 用来启动收发线程。因为我们需要实时获取收发信息,所以我们把对象存储到 Session 中,这样方便实时返回当前线程进行到什么程序,有些什么状态等:
[WebMethod(EnableSession = true)]
public string[] Start() {
HttpContext context = HttpContext.Current;
MailThread mail = null;
object mailObj = context.Session[MailHelper.POP3Name];
if (mailObj != null) {// 是否已经存在
mail = (MailThread)mailObj;
}
else {// 创建新的线程
mail = new MailThread();
context.Session.Add(MailHelper.POP3Name, mail);
mail.ReceiveStart();
}
if (mail.Pop3State >= 2) {// 接收完就不要了
mail.ReceiveStop();
context.Session.Remove(MailHelper.POP3Name);
}
return new string[] { mail.Pop3State.ToString(), mail.Pop3Mail, mail.Pop3Message };
}
[WebMethod(EnableSession = true)]
public string[] Start() {
HttpContext context = HttpContext.Current;
MailThread mail = null;
object mailObj = context.Session[MailHelper.SMTPName];
if (mailObj != null) {// 是否存在
mail = (MailThread)mailObj;
}
else {// 创建新的线程
mail = new MailThread(isstart);
context.Session.Add(MailHelper.SMTPName, mail);
mail.SendStart();
}
if (mail.SmtpState >= 2) {// 发送完就不要了
mail.SendStop();
context.Session.Remove(MailHelper.SMTPName);
}
return new string[] { mail.SmtpState.ToString(), mail.SmtpMail, mail.SmtpMessage };
}
好了,WebService 很简单。我们再来看看怎么调用:
首先向 Header.aspx 中添加 AJAX 控件 ScriptManager,然后添加两个 Service 引用:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Receiver.asmx" />
<asp:ServiceReference Path="~/Sender.asmx" />
Services>
asp:ScriptManager>
再添加两个实时信息栏:
<div id="POP3Div" style="display: none;">邮件接收信息栏div>
<div id="SMTPDiv" style="display: none;">邮件发送信息栏div>
<div id="SMTPDiv" style="display: none;">邮件发送信息栏div>
剩下的就是如何调用 WebService 向这两个信息栏中填充数据:
<script type="text/javascript" language="javascript">
function receiveMail(){
Receiver.Start(onPop3Success, onPop3Error);
}
function onPop3Success(result){
var pd = $get("POP3Div");
if(result[0]=="1"){
pd.style.display = "block";
pd.innerHTML = result[1]+result[2];
}else{
pd.style.display = "none";
}
}
function sendMail(){
Sender.Start(onSmtpSuccess, onSmtpError);
}
function onSmtpSuccess(result){
var pd = $get("SMTPDiv");
if(result[0]=="1"){
pd.style.display = "block";
pd.innerHTML = result[1]+result[2];
}else{
pd.style.display = "none";
}
}
function onPop3Error(error){
var pd = $get("POP3Div");
pd.style.display = "block";
pd.innerHTML = error.get_message();
}
function onSmtpError(error){
var pd = $get("SMTPDiv");
pd.style.display = "block";
pd.innerHTML = error.get_message();
}
function startThread(){
receiveMail();
sendMail();
}
// 1秒钟查一次,可以根据需求调整
window.setInterval("startThread();", 1*1000);
</script>