📄 localmailservice.cs
字号:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Mail;
using Db;
using System.Text;
namespace Mail
{
/// <summary>
/// Summary description for LocalMailService
/// </summary>
public class LocalMailService : MailService
{
private ServerSetting _smtp = new ServerSetting();
private ServerSetting _pop3 = new ServerSetting();
public LocalMailService(ServerSetting smtp, ServerSetting pop3)
{
this._smtp = smtp;
this._pop3 = pop3;
}
#region MailService Members
public bool SendMail(string from, string to, string subject, string body)
{
try
{
MailMessage msg = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient(_smtp.Host);
CredentialCache cache = new CredentialCache();
cache.Add(_smtp.Host, _smtp.Port, "Basic", new NetworkCredential(_smtp.Username, _smtp.Password, _smtp.Host));
client.Credentials = cache;
msg.IsBodyHtml = true;
msg.BodyEncoding = Encoding.UTF8;
client.Send(msg);
// TODO: 获取邮件大小
int size = msg.Headers.ToString().Length + msg.Body.Length;
size = (int)Math.Ceiling((double)(size / 1024));
// 邮件信息存入数据库
DbService dbService = new LocalDbService();
dbService.InsertMail(msg.From.Address, msg.To[0].Address, msg.Subject, msg.Body, 3, size);
}
catch (Exception)
{
return false;
}
return true;
}
public bool Test()
{
Pop3MimeClient client = new Pop3MimeClient(_pop3.Host, _pop3.Port, false, _pop3.Username + "@" + _pop3.Host, _pop3.Password);
client.ReadTimeout = 60000;
try
{
client.Connect();
}
catch (Exception)
{
return false;
}
finally
{
try
{
client.Disconnect();
}
catch (Exception)
{
}
}
return true;
}
public bool ReceiveMail()
{
Pop3MimeClient client = new Pop3MimeClient(_pop3.Host, _pop3.Port, false, _pop3.Username + "@" + _pop3.Host, _pop3.Password);
client.ReadTimeout = 60000;
try
{
client.Connect();
int numberOfMailsInMailbox, mailboxSize;
client.GetMailboxStats(out numberOfMailsInMailbox, out mailboxSize);
RxMailMessage msg;
int downloadNumberOfEmails;
int maxDownloadEmails = 99;
if (numberOfMailsInMailbox < maxDownloadEmails)
{
downloadNumberOfEmails = numberOfMailsInMailbox;
}
else
{
downloadNumberOfEmails = maxDownloadEmails;
}
for (int i = 1; i <= downloadNumberOfEmails; i++)
{
client.GetEmail(i, out msg);
if (msg != null)
{
// 获取邮件大小
int size = client.GetEmailSize(i);
size = (size + 512) / 1024;
// 邮件信息存入数据库
DbService dbService = new LocalDbService();
dbService.InsertMail(msg.From.Address, msg.To[0].Address, msg.Subject, msg.Body, 0, size);
// 从服务器上删除
client.DeleteEmail(i);
}
}
}
catch (Exception)
{
return false;
}
finally
{
try
{
client.Disconnect();
}
catch (Exception)
{
}
}
return true;
}
#endregion
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -