110,536
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.Sockets;
using System.IO;
using System.Net.Security;
using System.Text;
using System.Threading;
public partial class mail_GmailTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PopClient("pop.gmail.com", 995, "locoasta1984", "****");
}
static int PopClient(string serverAddr, int port, string userID, string password)
{
TcpClient clientSocket = new TcpClient();
StreamReader reader;
StreamWriter writer;
Stream pop3Stream;
clientSocket.Connect(serverAddr, port);
pop3Stream = new SslStream(clientSocket.GetStream(), false);
((SslStream)pop3Stream).AuthenticateAsClient(serverAddr); //这句是用来客户端验证的
reader = new StreamReader(pop3Stream, Encoding.Default, true);
writer = new StreamWriter(pop3Stream);
writer.AutoFlush = true;
Read(reader);
SendCommand(writer, "USER " + userID);
Read(reader);
SendCommand(writer, "PASS " + password);
Read(reader);
SendCommand(writer, "STAT ");
Read(reader);
SendCommand(writer, "LIST ");
//Read(reader);//这里进入判断有几封邮件 截取字符串
int mailNum = getList(reader);
if (mailNum > 0)
{
for (int i = 1; i <= mailNum; i++)
{
SendCommand(writer, "retr " + i.ToString());
string mail = getMailContent(reader); //这个就是邮件的内容 包括附件等等 需要解码
}
}
SendCommand(writer, "QUIT ");
Read(reader);
reader.Close();
writer.Close();
clientSocket.Close();
return 0;
}
private static string getMailContent(StreamReader reader)
{
string strResponse = string.Empty;
while (!reader.BaseStream.CanRead)
{
Thread.Sleep(1000);//网络好的话用不到这个
}
string strLine = reader.ReadLine();
strResponse = strLine;
while (reader.Peek() > 0)
{
strResponse += reader.ReadLine();
}
return strResponse;
}
private static int getList(StreamReader reader)
{
int num = 0;
string strResponse = string.Empty;
while (!reader.BaseStream.CanRead)
{
Thread.Sleep(1000);
}
strResponse = reader.ReadLine(); ;
while (reader.Peek() > 0)
{
strResponse += reader.ReadLine();
}
num =Int32.Parse(strResponse.Substring(4, 1));
return num;
}
static bool Read(StreamReader reader)
{
string strResponse = string.Empty;
while (!reader.BaseStream.CanRead)
{
Thread.Sleep(1000);//网络好的话用不到这个
}
strResponse = reader.ReadLine();
Console.WriteLine(strResponse);
if (strResponse.Substring(0, 3) != "+OK ")
{
return true;
}
else
{
return false;
}
}
static void SendCommand(StreamWriter writer, string cmd)
{
while (!writer.BaseStream.CanWrite)
{
Thread.Sleep(1000);
}
writer.WriteLine(cmd);
writer.Flush();
return;
}
}
using System.Data.SqlClient;
using faxapp.dataconn;
using faxapp.common;
using System.Net.Sockets;
using jmail;
using System.IO;
//收邮件完整代码:
public void ReceiveMails()
...{
jmail.Message Msg = new jmail.Message();
jmail.POP3 jpop = new jmail.POP3();
jmail.Attachments atts;
jmail.Attachment att;
//Mime m = new Mime();
//username为用户名,该方法通过用户名获取该用户的pop设置,即用户的POP用户名,密码,POP服务器地址以及端口号这四个参数,这四个参数是连接POP服务器的必用参数.
//SqlDataReader dataReader = this.ExtGetSetting(Username);
//if (dataReader.Read())
//{
// if (dataReader["PopServer"].ToString() != "" && dataReader["PopUsername"].ToString() != "")
// {
//连接POP服务器
MailAddress = System.Configuration.ConfigurationManager.AppSettings.Get("MailAddress");
MailFrom = System.Configuration.ConfigurationManager.AppSettings.Get("MailFrom");
POPAddress = System.Configuration.ConfigurationManager.AppSettings.Get("POPAddress");
STMPAddress = System.Configuration.ConfigurationManager.AppSettings.Get("STMPAddress");
MailUsername = System.Configuration.ConfigurationManager.AppSettings.Get("MailUsername");
MailPass = System.Configuration.ConfigurationManager.AppSettings.Get("MailPass");
Mailpassword=System.Configuration.ConfigurationManager.AppSettings.Get("Mailpassword");
string mailPopPort = System.Configuration.ConfigurationManager.AppSettings.Get("MailPopPort");
MailPopPort = Convert.ToInt32(mailPopPort);
jpop.Connect(MailUsername, Mailpassword, POPAddress, MailPopPort);
//如果服务器上有邮件
if (jpop.Count >= 1)
...{
for (int i = 1; i <= jpop.Count; i++)
...{
Msg = jpop.Messages[i];
atts = Msg.Attachments;
//取数据库中邮件信息中的最大发送时间,即最近接收到的一封邮件的时间
DataTable data = this.GetDataTable("select max(accepttime) from acceptfax where sendtag='1'");
//对服务器上的邮件的发送时间和数据库最近一封邮件的时间进行比较,如果大那么证明该邮件还未被收取,是一封新邮件,这样避免重复收取邮件入库
if (Msg.Date > Convert.ToDateTime(data.Rows[0][4].ToString()))
...{
//将这封新邮件的信息保存到数据库
//this.SaveExtMail(Msg, Username, dataReader["Email"].ToString(), jpop.GetMessageUID(i));
this.SaveExtMail(Msg.FromName, Msg.Subject, Msg.Body, Msg.Date.ToLongDateString());
//获取附件上传到服务器并且将信息存入数据库
if (atts.Count >= 1)
...{
for (int k = 0; k < atts.Count; k++)
...{
att = atts[k];//获得附件
string attname = att.Name;
try
...{
//Random TempNameInt = new Random();
//string NewMailDirName = TempNameInt.Next(100000000).ToString();
//生成随机文件后缀名
string strSaveDir = "\AttachFiles\";
//取得文件名(抱括路径)里最后一个"."的索引
int intExt = attname.LastIndexOf(".");
//取得文件扩展名
string strExt = attname.Substring(intExt);
//取得文件名(不包括路径)
Random objRand = new Random();
System.DateTime date = DateTime.Now;
//生成随机文件名
string str = attname.Substring(1, attname.LastIndexOf(".") - 1);
string saveName = System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString() + Convert.ToString(objRand.Next(99) * 97 + 100);
string strNewName = str + "(" + saveName + ")" + strExt;//取新名字,防止重复
Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(".") + "\AttachFiles\" + strNewName);
string mailPath = strSaveDir + strNewName;
att.SaveToFile(System.Web.HttpContext.Current.Server.MapPath(".") + mailPath);
//获取该封邮件在数据库的ID,以便和附件信息相对应,取邮件表中的最大ID即可
int mailID = this.GetMailID();
/**/////将附件信息存入数据库
this.AttExtSend(mailID, attname, att.Size, mailPath, Msg.From);
}
catch (Exception ex)
...{
throw new Exception(ex.Message);
}
}
}
}
}
}
//删除服务器上的邮件
jpop.DeleteMessages();
//断开连接
jpop.Disconnect();
// }
//}
}
//取数据库中邮件某个条件下的某条信息
public DataTable GetDataTable(string sqlstr)
...{
SqlConnection conn = sqlconn.CreateConn();
SqlDataAdapter da = new SqlDataAdapter(sqlstr , conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
dt.AcceptChanges();
conn.Close();
return dt;
}
//将新邮件的信息保存到数据库acceptfax表中
public void SaveExtMail(string FromName, string Subject, string Body, string Date)
...{
//-----------------------更新到数据库中-------------------------
SqlConnection conn = sqlconn.CreateConn();
SqlDataAdapter da = new SqlDataAdapter("select * from acceptfax", conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
DataRow dr = dt.NewRow();
dr["faxno"] = FromName;
dr["title"] = Subject;
dr["content"] = Body;
dr["accepttime"] = Date;
dt.Rows.Add(dr);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
da.Update(dt);
dt.AcceptChanges();
conn.Close();
}
//获取该邮件的在数据库中的ID号,便与和附件相对应
public int GetMailID()
...{
//取数据库中邮件信息中的最大发送时间,即最近接收到的一封邮件的时间,得到该邮件sid号
DataTable data = this.GetDataTable("select max(accepttime) from acceptfax where sendtag='1'");
int result = Convert.ToInt32(data.Rows[0][0].ToString());
return result;
}
//把每个附件的内容更新入数据库
public void AttExtSend(int mailID,string attname,int Size,string mailpath,string format)
...{
//-----------------------更新到数据库中-------------------------
SqlConnection conn = sqlconn.CreateConn();
SqlDataAdapter da = new SqlDataAdapter("select * from attachmentInfo", conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
DataRow dr = dt.NewRow();
dr["mailID"] = mailID;
dr["attname"] = attname;
dr["attsize"] = Size;
dr["mailpath"] = mailpath;
dr["format"] = format;
dt.Rows.Add(dr);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
da.Update(dt);
dt.AcceptChanges();
conn.Close();
}