private void button1_Click(object sender, EventArgs e)
{
OleDbConnection oleDbConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Base de datos especial.mdb");
foreach (DataRow row in base_de_datos_especialDataSet.Tabla1.Rows)
{
string name = row[1].ToString();
OleDbCommand oleDbCommand = new OleDbCommand();
oleDbCommand.Connection = oleDbConnection;
oleDbCommand.CommandText = "INSERT INTO Tabla2 ( Nombre, Identificador) VALUES ('name', 2)";
oleDbConnection.Open();
oleDbCommand.ExecuteNonQuery();
oleDbConnection.Close();
}
base_de_datos_especialDataSet.AcceptChanges();
tabla2TableAdapter.Update(base_de_datos_especialDataSet);
this.tabla2TableAdapter.Fill(this.base_de_datos_especialDataSet.Tabla2);
miércoles, 4 de agosto de 2010
domingo, 11 de abril de 2010
S/MIME signature validate
private void getsignature(string Email)
{
//Extract signature
MIME.MimeMessage aMimeMessage = new MIME.MimeMessage();
aMimeMessage.LoadBody(Email);
string boundary = aMimeMessage.GetBoundary();
ArrayList bodylist = new ArrayList();
aMimeMessage.GetBodyPartList(bodylist);
MimeBody ab = (MimeBody)bodylist[bodylist.Count-1];
string prueba = ab.GetRawContent();
//Extract signed part
int start = Email.IndexOf("Content-Type:");
start = Email.IndexOf("Content-Type:",start+1);
string signedcontent = Email.Substring(start);
int last = signedcontent.LastIndexOf(boundary);
signedcontent = signedcontent.Remove(last - 2);
last = signedcontent.LastIndexOf(boundary);
signedcontent = signedcontent.Remove(last - 4);
byte[] bytFirma = Convert.FromBase64String(prueba);
ContentInfo objContent = new ContentInfo(Encoding.ASCII.GetBytes(signedcontent));
SignedCms objDatos = new SignedCms(objContent,true);
objDatos.Decode(bytFirma);
try
{
objDatos.CheckSignature(true);
MessageBox.Show("Ok - La firma concuerda con los datos");
MessageBox.Show(Encoding.ASCII.GetString(objDatos.ContentInfo.Content));
}
catch
{
MessageBox.Show("Error - La firma no concuerda con los datos");
}
}
{
//Extract signature
MIME.MimeMessage aMimeMessage = new MIME.MimeMessage();
aMimeMessage.LoadBody(Email);
string boundary = aMimeMessage.GetBoundary();
ArrayList bodylist = new ArrayList();
aMimeMessage.GetBodyPartList(bodylist);
MimeBody ab = (MimeBody)bodylist[bodylist.Count-1];
string prueba = ab.GetRawContent();
//Extract signed part
int start = Email.IndexOf("Content-Type:");
start = Email.IndexOf("Content-Type:",start+1);
string signedcontent = Email.Substring(start);
int last = signedcontent.LastIndexOf(boundary);
signedcontent = signedcontent.Remove(last - 2);
last = signedcontent.LastIndexOf(boundary);
signedcontent = signedcontent.Remove(last - 4);
byte[] bytFirma = Convert.FromBase64String(prueba);
ContentInfo objContent = new ContentInfo(Encoding.ASCII.GetBytes(signedcontent));
SignedCms objDatos = new SignedCms(objContent,true);
objDatos.Decode(bytFirma);
try
{
objDatos.CheckSignature(true);
MessageBox.Show("Ok - La firma concuerda con los datos");
MessageBox.Show(Encoding.ASCII.GetString(objDatos.ContentInfo.Content));
}
catch
{
MessageBox.Show("Error - La firma no concuerda con los datos");
}
}
lunes, 5 de abril de 2010
Delete mails from server
private void button1_Click(object sender, EventArgs e)
{
Pop3MailClient client = new Pop3MailClient("localhost", 110, false, "stpaul", "stpaul");
client.Connect();
client.DeleteEmail((int)dataGridView1.CurrentRow.Cells[3].Value);
List EmailIds;
client.GetEmailIdList(out EmailIds);
dataGridView1.Rows.Clear();
foreach (int Id in EmailIds)
{
string Email;
client.GetRawEmail(Id, out Email);
MIME.MimeMessage aMimeMessage = new MIME.MimeMessage();
aMimeMessage.LoadBody(Email);
ArrayList bodylist = new ArrayList();
aMimeMessage.GetBodyPartList(bodylist);
this.dataGridView1.Rows.Add(aMimeMessage.GetSubject(), aMimeMessage.GetFrom(), aMimeMessage.GetDate(), Id);
}
client.Disconnect();
}
{
Pop3MailClient client = new Pop3MailClient("localhost", 110, false, "stpaul", "stpaul");
client.Connect();
client.DeleteEmail((int)dataGridView1.CurrentRow.Cells[3].Value);
List
client.GetEmailIdList(out EmailIds);
dataGridView1.Rows.Clear();
foreach (int Id in EmailIds)
{
string Email;
client.GetRawEmail(Id, out Email);
MIME.MimeMessage aMimeMessage = new MIME.MimeMessage();
aMimeMessage.LoadBody(Email);
ArrayList bodylist = new ArrayList();
aMimeMessage.GetBodyPartList(bodylist);
this.dataGridView1.Rows.Add(aMimeMessage.GetSubject(), aMimeMessage.GetFrom(), aMimeMessage.GetDate(), Id);
}
client.Disconnect();
}
List Mails in Inbox
private void button6_Click(object sender, EventArgs e)
{
Pop3MailClient client = new Pop3MailClient("localhost", 110, false, "stpaul", "stpaul");
client.Connect();
//int NumberOfMails, MailboxSize;
//client.GetMailboxStats(out NumberOfMails, out MailboxSize);
List EmailIds;
client.GetEmailIdList(out EmailIds);
dataGridView1.Rows.Clear();
foreach (int Id in EmailIds)
{
string Email;
client.GetRawEmail(Id, out Email);
MIME.MimeMessage aMimeMessage = new MIME.MimeMessage();
aMimeMessage.LoadBody(Email);
ArrayList bodylist = new ArrayList();
aMimeMessage.GetBodyPartList(bodylist);
this.dataGridView1.Rows.Add(aMimeMessage.GetSubject(), aMimeMessage.GetFrom(), aMimeMessage.GetDate(), Id);
}
client.Disconnect();
}
{
Pop3MailClient client = new Pop3MailClient("localhost", 110, false, "stpaul", "stpaul");
client.Connect();
//int NumberOfMails, MailboxSize;
//client.GetMailboxStats(out NumberOfMails, out MailboxSize);
List
client.GetEmailIdList(out EmailIds);
dataGridView1.Rows.Clear();
foreach (int Id in EmailIds)
{
string Email;
client.GetRawEmail(Id, out Email);
MIME.MimeMessage aMimeMessage = new MIME.MimeMessage();
aMimeMessage.LoadBody(Email);
ArrayList bodylist = new ArrayList();
aMimeMessage.GetBodyPartList(bodylist);
this.dataGridView1.Rows.Add(aMimeMessage.GetSubject(), aMimeMessage.GetFrom(), aMimeMessage.GetDate(), Id);
}
client.Disconnect();
}
Pop3MailClient.cs - Fast POP3 for c#!!!
// POP3 Client
// ===========
//
// copyright by Peter Huber, Singapore, 2006
// this code is provided as is, bugs are probable, free for any use, no responsibility accepted :-)
//
// based on POP3 Client as a C# Class, by Bill Dean, http://www.codeproject.com/csharp/Pop3MailClient.asp
// based on Retrieve Mail From a POP3 Server Using C#, by Agus Kurniawan, http://www.codeproject.com/csharp/popapp.asp
// based on Post Office Protocol - Version 3, http://www.ietf.org/rfc/rfc1939.txt
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Text;
// Supporting classes and structs
// ==============================
///
/// Combines Email ID with Email UID for one email
/// The POP3 server assigns to each message a unique Email UID, which will not change for the life time
/// of the message and no other message should use the same.
///
/// Exceptions:
/// Throws Pop3Exception if there is a serious communication problem with the POP3 server, otherwise
///
///
public struct EmailUid {
///
/// used in POP3 commands to indicate which message (only valid in the present session)
///
public int EmailId;
///
/// Uid is always the same for a message, regardless of session
///
public string Uid;
///
///
///
///
///
public EmailUid(int EmailId, string Uid) {
this.EmailId = EmailId;
this.Uid = Uid;
}
}
///
/// If anything goes wrong within Pop3MailClient, a Pop3Exception is raised
///
public class Pop3Exception2:ApplicationException {
///
///
///
public Pop3Exception2() { }
///
///
///
///
public Pop3Exception2(string ErrorMessage) : base(ErrorMessage) { }
}
///
/// A pop 3 connection goes through the following states:
///
public enum Pop3ConnectionStateEnum {
///
/// undefined
///
None=0,
///
/// not connected yet to POP3 server
///
Disconnected,
///
/// TCP connection has been opened and the POP3 server has sent the greeting. POP3 server expects user name and password
///
Authorization,
///
/// client has identified itself successfully with the POP3, server has locked all messages
///
Connected,
///
/// QUIT command was sent, the server has deleted messages marked for deletion and released the resources
///
Closed
}
// Delegates for Pop3MailClient
// ============================
///
/// If POP3 Server doesn't react as expected or this code has a problem, but
/// can continue with the execution, a Warning is called.
///
///
/// string received from POP3 server
public delegate void WarningHandler(string WarningText, string Response);
///
/// Traces all the information exchanged between POP3 client and POP3 server plus some
/// status messages from POP3 client.
/// Helpful to investigate any problem.
/// Console.WriteLine() can be used
///
///
public delegate void TraceHandler(string TraceText);
// Pop3MailClient Class
// ====================
///
/// provides access to emails on a POP3 Server
///
public class Pop3MailClient {
//Events
//------
///
/// Called whenever POP3 server doesn't react as expected, but no runtime error is thrown.
///
public event WarningHandler Warning;
///
/// call warning event
///
/// name of the method where warning is needed
/// answer from POP3 server causing the warning
/// explanation what went wrong
///
protected void CallWarning(string methodName, string response, string warningText, params object[] warningParameters) {
warningText = string.Format(warningText, warningParameters);
if (Warning!=null) {
Warning(methodName + ": " + warningText, response);
}
CallTrace("!! {0}", warningText);
}
///
/// Shows the communication between PopClient and PopServer, including warnings
///
public event TraceHandler Trace;
///
/// call Trace event
///
/// string to be traced
///
protected void CallTrace(string text, params object[] parameters) {
if (Trace!=null) {
Trace(DateTime.Now.ToString("hh:mm:ss ") + popServer + " " + string.Format(text, parameters));
}
}
///
/// Trace information received from POP3 server
///
/// string to be traced
///
protected void TraceFrom(string text, params object[] parameters) {
if (Trace!=null) {
CallTrace(" " + string.Format(text, parameters));
}
}
//Properties
//----------
///
/// Get POP3 server name
///
public string PopServer {
get { return popServer; }
}
///
/// POP3 server name
///
protected string popServer;
///
/// Get POP3 server port
///
public int Port {
get { return port; }
}
///
/// POP3 server port
///
protected int port;
///
/// Should SSL be used for connection with POP3 server ?
///
public bool UseSSL {
get { return useSSL; }
}
///
/// Should SSL be used for connection with POP3 server ?
///
private bool useSSL;
///
/// should Pop3MailClient automatically reconnect if POP3 server has dropped the
/// connection due to a timeout ?
///
public bool IsAutoReconnect {
get { return isAutoReconnect; }
set { isAutoReconnect = value; }
}
private bool isAutoReconnect = false;
//timeout has occured, we try to perform an autoreconnect
private bool isTimeoutReconnect = false;
///
/// Get / set read timeout (miliseconds)
///
public int ReadTimeout {
get { return readTimeout; }
set {
readTimeout = value;
if (pop3Stream!=null && pop3Stream.CanTimeout) {
pop3Stream.ReadTimeout = readTimeout;
}
}
}
///
/// POP3 server read timeout
///
protected int readTimeout = -1;
///
/// Get owner name of mailbox on POP3 server
///
public string Username {
get { return username; }
}
///
/// Owner name of mailbox on POP3 server
///
protected string username;
///
/// Get password for mailbox on POP3 server
///
public string Password {
get { return password; }
}
///
/// Password for mailbox on POP3 server
///
protected string password;
///
/// Get connection status with POP3 server
///
public Pop3ConnectionStateEnum Pop3ConnectionState {
get { return pop3ConnectionState; }
}
///
/// connection status with POP3 server
///
protected Pop3ConnectionStateEnum pop3ConnectionState = Pop3ConnectionStateEnum.Disconnected;
// Methods
// -------
///
/// set POP3 connection state
///
///
protected void setPop3ConnectionState(Pop3ConnectionStateEnum State) {
pop3ConnectionState = State;
CallTrace(" Pop3MailClient Connection State {0} reached", State);
}
///
/// throw exception if POP3 connection is not in the required state
///
///
protected void EnsureState(Pop3ConnectionStateEnum requiredState) {
if (pop3ConnectionState!=requiredState) {
// wrong connection state
throw new Pop3Exception("GetMailboxStats only accepted during connection state: " + requiredState.ToString() +
"\n The connection to server "+ popServer + " is in state " + pop3ConnectionState.ToString());
}
}
//private fields
//--------------
///
/// TCP to POP3 server
///
private TcpClient serverTcpConnection;
///
/// Stream from POP3 server with or without SSL
///
private Stream pop3Stream;
///
/// Reader for POP3 message
///
protected StreamReader pop3StreamReader;
///
/// char 'array' for carriage return / line feed
///
protected string CRLF = "\r\n";
//public methods
//--------------
///
/// Make POP3 client ready to connect to POP3 server
///
///pop.gmail.com
///995
/// True: SSL is used for connection to POP3 server
///abc@gmail.com
/// Secret
public Pop3MailClient(string PopServer, int Port, bool useSSL, string Username, string Password) {
this.popServer = PopServer;
this.port = Port;
this.useSSL = useSSL;
this.username = Username;
this.password = Password;
}
///
/// Connect to POP3 server
///
public void Connect() {
if (pop3ConnectionState!=Pop3ConnectionStateEnum.Disconnected &&
pop3ConnectionState!=Pop3ConnectionStateEnum.Closed &&
!isTimeoutReconnect) {
CallWarning("connect", "", "Connect command received, but connection state is: " + pop3ConnectionState.ToString());
} else {
//establish TCP connection
try {
CallTrace(" Connect at port {0}", port);
serverTcpConnection = new TcpClient(popServer, port);
} catch (Exception ex) {
throw new Pop3Exception("Connection to server "+ popServer + ", port " + port + " failed.\nRuntime Error: "+ex.ToString());
}
if (useSSL) {
//get SSL stream
try {
CallTrace(" Get SSL connection");
pop3Stream = new SslStream(serverTcpConnection.GetStream(), false);
pop3Stream.ReadTimeout = readTimeout;
} catch (Exception ex) {
throw new Pop3Exception("Server " + popServer + " found, but cannot get SSL data stream.\nRuntime Error: "+ex.ToString());
}
//perform SSL authentication
try {
CallTrace(" Get SSL authentication");
((SslStream)pop3Stream).AuthenticateAsClient(popServer);
} catch (Exception ex) {
throw new Pop3Exception("Server " + popServer + " found, but problem with SSL Authentication.\nRuntime Error: " + ex.ToString());
}
} else {
//create a stream to POP3 server without using SSL
try {
CallTrace(" Get connection without SSL");
pop3Stream = serverTcpConnection.GetStream();
pop3Stream.ReadTimeout = readTimeout;
} catch (Exception ex) {
throw new Pop3Exception("Server " + popServer + " found, but cannot get data stream (without SSL).\nRuntime Error: "+ex.ToString());
}
}
//get stream for reading from pop server
//POP3 allows only US-ASCII. The message will be translated in the proper encoding in a later step
try {
pop3StreamReader= new StreamReader(pop3Stream, Encoding.ASCII);
} catch (Exception ex) {
if (useSSL) {
throw new Pop3Exception("Server " + popServer + " found, but cannot read from SSL stream.\nRuntime Error: " + ex.ToString());
} else {
throw new Pop3Exception("Server " + popServer + " found, but cannot read from stream (without SSL).\nRuntime Error: " + ex.ToString());
}
}
//ready for authorisation
string response;
if (!readSingleLine(out response)) {
throw new Pop3Exception("Server " + popServer + " not ready to start AUTHORIZATION.\nMessage: " + response);
}
setPop3ConnectionState(Pop3ConnectionStateEnum.Authorization);
//send user name
if (!executeCommand("USER "+ username, out response)) {
throw new Pop3Exception("Server " + popServer + " doesn't accept username '" + username + "'.\nMessage: " + response);
}
//send password
if (!executeCommand("PASS " + password, out response)) {
throw new Pop3Exception("Server " + popServer + " doesn't accept password '" + password + "' for user '" + username + "'.\nMessage: " + response);
}
setPop3ConnectionState(Pop3ConnectionStateEnum.Connected);
}
}
///
/// Disconnect from POP3 Server
///
public void Disconnect() {
if (pop3ConnectionState==Pop3ConnectionStateEnum.Disconnected ||
pop3ConnectionState==Pop3ConnectionStateEnum.Closed) {
CallWarning("disconnect", "", "Disconnect received, but was already disconnected.");
} else {
//ask server to end session and possibly to remove emails marked for deletion
try {
string response;
if (executeCommand("QUIT", out response)) {
//server says everything is ok
setPop3ConnectionState(Pop3ConnectionStateEnum.Closed);
} else {
//server says there is a problem
CallWarning("Disconnect", response, "negative response from server while closing connection: " + response);
setPop3ConnectionState(Pop3ConnectionStateEnum.Disconnected);
}
} finally {
//close connection
if (pop3Stream!=null) {
pop3Stream.Close();
}
pop3StreamReader.Close();
}
}
}
///
/// Delete message from server.
/// The POP3 server marks the message as deleted. Any future
/// reference to the message-number associated with the message
/// in a POP3 command generates an error. The POP3 server does
/// not actually delete the message until the POP3 session
/// enters the UPDATE state.
///
///
///
public bool DeleteEmail(int msg_number) {
EnsureState(Pop3ConnectionStateEnum.Connected);
string response;
if (!executeCommand("DELE " + msg_number.ToString(), out response)) {
CallWarning("DeleteEmail", response, "negative response for email (Id: {0}) delete request", msg_number);
return false;
}
return true;
}
///
/// Get a list of all Email IDs available in mailbox
///
///
public bool GetEmailIdList(out List EmailIds) {
EnsureState(Pop3ConnectionStateEnum.Connected);
EmailIds = new List();
//get server response status line
string response;
if (!executeCommand("LIST", out response)) {
CallWarning("GetEmailIdList", response, "negative response for email list request");
return false;
}
//get every email id
int EmailId;
while (readMultiLine(out response)) {
if (int.TryParse(response.Split(' ')[0], out EmailId)) {
EmailIds.Add(EmailId);
} else {
CallWarning("GetEmailIdList", response, "first characters should be integer (EmailId)");
}
}
TraceFrom("{0} email ids received", EmailIds.Count);
return true;
}
///
/// get size of one particular email
///
///
///
public int GetEmailSize(int msg_number) {
EnsureState(Pop3ConnectionStateEnum.Connected);
string response;
executeCommand("LIST " + msg_number.ToString(), out response);
int EmailSize = 0;
string[] responseSplit = response.Split(' ');
if (responseSplit.Length<2>
/// Get a list with the unique IDs of all Email available in mailbox.
///
/// Explanation:
/// EmailIds for the same email can change between sessions, whereas the unique Email id
/// never changes for an email.
///
///
///
public bool GetUniqueEmailIdList(out List EmailIds) {
EnsureState(Pop3ConnectionStateEnum.Connected);
EmailIds = new List();
//get server response status line
string response;
if (!executeCommand("UIDL ", out response)) {
CallWarning("GetUniqueEmailIdList", response, "negative response for email list request");
return false;
}
//get every email unique id
int EmailId;
while (readMultiLine(out response)) {
string[] responseSplit = response.Split(' ');
if (responseSplit.Length<2)>
/// get a list with all currently available messages and the UIDs
///
/// EmailId Uid list
///false: server sent negative response (didn't send list)
public bool GetUniqueEmailIdList(out SortedList EmailIds) {
EnsureState(Pop3ConnectionStateEnum.Connected);
EmailIds = new SortedList();
//get server response status line
string response;
if (!executeCommand("UIDL", out response)) {
CallWarning("GetUniqueEmailIdList", response, "negative response for email list request");
return false;
}
//get every email unique id
int EmailId;
while (readMultiLine(out response)) {
string[] responseSplit = response.Split(' ');
if (responseSplit.Length<2)>
/// get size of one particular email
///
///
///
public int GetUniqueEmailId(EmailUid msg_number) {
EnsureState(Pop3ConnectionStateEnum.Connected);
string response;
executeCommand("LIST " + msg_number.ToString(), out response);
int EmailSize = 0;
string[] responseSplit = response.Split(' ');
if (responseSplit.Length<2>
/// Sends an 'empty' command to the POP3 server. Server has to respond with +OK
///
///true: server responds as expected
public bool NOOP() {
EnsureState(Pop3ConnectionStateEnum.Connected);
string response;
if (!executeCommand("NOOP", out response)) {
CallWarning("NOOP", response, "negative response for NOOP request");
return false;
}
return true;
}
///
/// Should the raw content, the US-ASCII code as received, be traced
/// GetRawEmail will switch it on when it starts and off once finished
///
/// Inheritors might use it to get the raw email
///
protected bool isTraceRawEmail = false;
///
/// contains one MIME part of the email in US-ASCII, needs to be translated in .NET string (Unicode)
/// contains the complete email in US-ASCII, needs to be translated in .NET string (Unicode)
/// For speed reasons, reuse StringBuilder
///
protected StringBuilder RawEmailSB;
///
/// Reads the complete text of a message
///
/// Email to retrieve
/// ASCII string of complete message
///
public bool GetRawEmail(int MessageNo, out string EmailText) {
//send 'RETR int' command to server
if (!SendRetrCommand(MessageNo)) {
EmailText = null;
return false;
}
//get the lines
string response;
int LineCounter = 0;
//empty StringBuilder
if (RawEmailSB==null) {
RawEmailSB = new StringBuilder(100000);
} else {
RawEmailSB.Length = 0;
}
isTraceRawEmail = true;
while (readMultiLine(out response)) {
LineCounter += 1;
}
EmailText = RawEmailSB.ToString();
TraceFrom("email with {0} lines, {1} chars received", LineCounter.ToString(), EmailText.Length);
return true;
}
/////
///// Requests from POP3 server a specific email and returns a stream with the message content (header and body)
/////
/////
/////
/////false: POP3 server cannot provide this message
//public bool GetEmailStream(int MessageNo, out StreamReader EmailStreamReader) {
// //send 'RETR int' command to server
// if (!SendRetrCommand(MessageNo)) {
// EmailStreamReader = null;
// return false;
// }
// EmailStreamReader = sslStreamReader;
// return true;
//}
///
/// Unmark any emails from deletion. The server only deletes email really
/// once the connection is properly closed.
///
///true: emails are unmarked from deletion
public bool UndeleteAllEmails() {
EnsureState(Pop3ConnectionStateEnum.Connected);
string response;
return executeCommand("RSET", out response);
}
///
/// Get mailbox statistics
///
///
///
///
public bool GetMailboxStats(out int NumberOfMails, out int MailboxSize) {
EnsureState(Pop3ConnectionStateEnum.Connected);
//interpret response
string response;
NumberOfMails = 0;
MailboxSize =0;
if (executeCommand("STAT", out response)) {
//got a positive response
string[] responseParts = response.Split(' ');
if (responseParts.Length<2) numberofmails =" int.Parse(responseParts[1]);" mailboxsize =" int.Parse(responseParts[2]);">
/// Send RETR command to POP 3 server to fetch one particular message
///
/// ID of message required
///false: negative server respond, message not delivered
protected bool SendRetrCommand(int MessageNo) {
EnsureState(Pop3ConnectionStateEnum.Connected);
// retrieve mail with message number
string response;
if (!executeCommand("RETR "+ MessageNo.ToString(), out response)) {
CallWarning("GetRawEmail", response, "negative response for email (ID: {0}) request", MessageNo);
return false;
}
return true;
}
//Helper methodes
//---------------
///
/// sends the 4 letter command to POP3 server (adds CRLF) and waits for the
/// response of the server
///
/// command to be sent to server
/// answer from server
///false: server sent negative acknowledge, i.e. server could not execute command
public bool isDebug = false;
private bool executeCommand(string command, out string response) {
//send command to server
byte[] commandBytes = System.Text.Encoding.ASCII.GetBytes((command + CRLF).ToCharArray());
CallTrace("Tx '{0}'", command);
bool isSupressThrow = false;
try {
pop3Stream.Write(commandBytes, 0, commandBytes.Length);
if (isDebug) {
isDebug=false;
throw new IOException("Test", new SocketException(10053));
}
} catch (IOException ex) {
//Unable to write data to the transport connection. Check if reconnection should be tried
isSupressThrow = executeReconnect(ex, command, commandBytes);
if (!isSupressThrow) {
throw;
}
}
pop3Stream.Flush();
//read response from server
response = null;
try {
response = pop3StreamReader.ReadLine();
} catch (IOException ex) {
//Unable to write data to the transport connection. Check if reconnection should be tried
isSupressThrow = executeReconnect(ex, command, commandBytes);
if (isSupressThrow) {
//wait for response one more time
response = pop3StreamReader.ReadLine();
} else {
throw;
}
}
if (response==null) {
throw new Pop3Exception("Server "+ popServer + " has not responded, timeout has occured.");
}
CallTrace("Rx '{0}'", response);
return (response.Length>0 && response[0]=='+');
}
///
/// reconnect, if there is a timeout exception and isAutoReconnect is true
///
///
private bool executeReconnect(IOException ex, string command, byte[] commandBytes) {
if (ex.InnerException!=null && ex.InnerException is SocketException) {
//SocketException
SocketException innerEx = (SocketException)ex.InnerException;
if (innerEx.ErrorCode==10053) {
//probably timeout: An established connection was aborted by the software in your host machine.
CallWarning("ExecuteCommand", "", "probably timeout occured");
if (isAutoReconnect) {
//try to reconnect and send one more time
isTimeoutReconnect = true;
try {
CallTrace(" try to auto reconnect");
Connect();
CallTrace(" reconnect successful, try to resend command");
CallTrace("Tx '{0}'", command);
pop3Stream.Write(commandBytes, 0, commandBytes.Length);
pop3Stream.Flush();
return true;
} finally {
isTimeoutReconnect = false;
}
}
}
}
return false;
}
/*
///
/// sends the 4 letter command to POP3 server (adds CRLF)
///
///
protected void SendCommand(string command) {
byte[] commandBytes = System.Text.Encoding.ASCII.GetBytes((command + CRLF).ToCharArray());
CallTrace("Tx '{0}'", command);
try {
pop3Stream.Write(commandBytes, 0, commandBytes.Length);
} catch (IOException ex) {
//Unable to write data to the transport connection:
if (ex.InnerException!=null && ex.InnerException is SocketException) {
//SocketException
SocketException innerEx = (SocketException)ex.InnerException;
if (innerEx.ErrorCode==10053) {
//probably timeout: An established connection was aborted by the software in your host machine.
CallWarning("SendCommand", "", "probably timeout occured");
if (isAutoReconnect) {
//try to reconnect and send one more time
isTimeoutReconnect = true;
try {
CallTrace(" try to auto reconnect");
Connect();
CallTrace(" reconnect successful, try to resend command");
CallTrace("Tx '{0}'", command);
pop3Stream.Write(commandBytes, 0, commandBytes.Length);
} finally {
isTimeoutReconnect = false;
}
return;
}
}
}
throw;
}
pop3Stream.Flush();
}
*/
///
/// read single line response from POP3 server.
///Example server response: +OK asdfkjahsf
///
/// response from POP3 server
///true: positive response
protected bool readSingleLine(out string response) {
response = null;
try {
response = pop3StreamReader.ReadLine();
} catch (Exception ex) {
string s = ex.Message;
}
if (response==null) {
throw new Pop3Exception("Server "+ popServer + " has not responded, timeout has occured.");
}
CallTrace("Rx '{0}'", response);
return (response.Length>0 && response[0]=='+');
}
///
/// read one line in multiline mode from the POP3 server.
///
/// line received
///false: end of message
///
protected bool readMultiLine(out string response) {
response = null;
response = pop3StreamReader.ReadLine();
if (response==null) {
throw new Pop3Exception("Server "+ popServer + " has not responded, probably timeout has occured.");
}
if (isTraceRawEmail) {
//collect all responses as received
RawEmailSB.Append(response + CRLF);
}
//check for byte stuffing, i.e. if a line starts with a '.', another '.' is added, unless
//it is the last line
if (response.Length>0 && response[0]=='.') {
if (response==".") {
//closing line found
return false;
}
//remove the first '.'
response = response.Substring(1, response.Length-1);
}
return true;
}
}
// ===========
//
// copyright by Peter Huber, Singapore, 2006
// this code is provided as is, bugs are probable, free for any use, no responsibility accepted :-)
//
// based on POP3 Client as a C# Class, by Bill Dean, http://www.codeproject.com/csharp/Pop3MailClient.asp
// based on Retrieve Mail From a POP3 Server Using C#, by Agus Kurniawan, http://www.codeproject.com/csharp/popapp.asp
// based on Post Office Protocol - Version 3, http://www.ietf.org/rfc/rfc1939.txt
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Text;
// Supporting classes and structs
// ==============================
///
/// Combines Email ID with Email UID for one email
/// The POP3 server assigns to each message a unique Email UID, which will not change for the life time
/// of the message and no other message should use the same.
///
/// Exceptions:
/// Throws Pop3Exception if there is a serious communication problem with the POP3 server, otherwise
///
///
public struct EmailUid {
///
/// used in POP3 commands to indicate which message (only valid in the present session)
///
public int EmailId;
///
/// Uid is always the same for a message, regardless of session
///
public string Uid;
///
///
///
///
///
public EmailUid(int EmailId, string Uid) {
this.EmailId = EmailId;
this.Uid = Uid;
}
}
///
/// If anything goes wrong within Pop3MailClient, a Pop3Exception is raised
///
public class Pop3Exception2:ApplicationException {
///
///
///
public Pop3Exception2() { }
///
///
///
///
public Pop3Exception2(string ErrorMessage) : base(ErrorMessage) { }
}
///
/// A pop 3 connection goes through the following states:
///
public enum Pop3ConnectionStateEnum {
///
/// undefined
///
None=0,
///
/// not connected yet to POP3 server
///
Disconnected,
///
/// TCP connection has been opened and the POP3 server has sent the greeting. POP3 server expects user name and password
///
Authorization,
///
/// client has identified itself successfully with the POP3, server has locked all messages
///
Connected,
///
/// QUIT command was sent, the server has deleted messages marked for deletion and released the resources
///
Closed
}
// Delegates for Pop3MailClient
// ============================
///
/// If POP3 Server doesn't react as expected or this code has a problem, but
/// can continue with the execution, a Warning is called.
///
///
/// string received from POP3 server
public delegate void WarningHandler(string WarningText, string Response);
///
/// Traces all the information exchanged between POP3 client and POP3 server plus some
/// status messages from POP3 client.
/// Helpful to investigate any problem.
/// Console.WriteLine() can be used
///
///
public delegate void TraceHandler(string TraceText);
// Pop3MailClient Class
// ====================
///
/// provides access to emails on a POP3 Server
///
public class Pop3MailClient {
//Events
//------
///
/// Called whenever POP3 server doesn't react as expected, but no runtime error is thrown.
///
public event WarningHandler Warning;
///
/// call warning event
///
/// name of the method where warning is needed
/// answer from POP3 server causing the warning
/// explanation what went wrong
///
protected void CallWarning(string methodName, string response, string warningText, params object[] warningParameters) {
warningText = string.Format(warningText, warningParameters);
if (Warning!=null) {
Warning(methodName + ": " + warningText, response);
}
CallTrace("!! {0}", warningText);
}
///
/// Shows the communication between PopClient and PopServer, including warnings
///
public event TraceHandler Trace;
///
/// call Trace event
///
/// string to be traced
///
protected void CallTrace(string text, params object[] parameters) {
if (Trace!=null) {
Trace(DateTime.Now.ToString("hh:mm:ss ") + popServer + " " + string.Format(text, parameters));
}
}
///
/// Trace information received from POP3 server
///
/// string to be traced
///
protected void TraceFrom(string text, params object[] parameters) {
if (Trace!=null) {
CallTrace(" " + string.Format(text, parameters));
}
}
//Properties
//----------
///
/// Get POP3 server name
///
public string PopServer {
get { return popServer; }
}
///
/// POP3 server name
///
protected string popServer;
///
/// Get POP3 server port
///
public int Port {
get { return port; }
}
///
/// POP3 server port
///
protected int port;
///
/// Should SSL be used for connection with POP3 server ?
///
public bool UseSSL {
get { return useSSL; }
}
///
/// Should SSL be used for connection with POP3 server ?
///
private bool useSSL;
///
/// should Pop3MailClient automatically reconnect if POP3 server has dropped the
/// connection due to a timeout ?
///
public bool IsAutoReconnect {
get { return isAutoReconnect; }
set { isAutoReconnect = value; }
}
private bool isAutoReconnect = false;
//timeout has occured, we try to perform an autoreconnect
private bool isTimeoutReconnect = false;
///
/// Get / set read timeout (miliseconds)
///
public int ReadTimeout {
get { return readTimeout; }
set {
readTimeout = value;
if (pop3Stream!=null && pop3Stream.CanTimeout) {
pop3Stream.ReadTimeout = readTimeout;
}
}
}
///
/// POP3 server read timeout
///
protected int readTimeout = -1;
///
/// Get owner name of mailbox on POP3 server
///
public string Username {
get { return username; }
}
///
/// Owner name of mailbox on POP3 server
///
protected string username;
///
/// Get password for mailbox on POP3 server
///
public string Password {
get { return password; }
}
///
/// Password for mailbox on POP3 server
///
protected string password;
///
/// Get connection status with POP3 server
///
public Pop3ConnectionStateEnum Pop3ConnectionState {
get { return pop3ConnectionState; }
}
///
/// connection status with POP3 server
///
protected Pop3ConnectionStateEnum pop3ConnectionState = Pop3ConnectionStateEnum.Disconnected;
// Methods
// -------
///
/// set POP3 connection state
///
///
protected void setPop3ConnectionState(Pop3ConnectionStateEnum State) {
pop3ConnectionState = State;
CallTrace(" Pop3MailClient Connection State {0} reached", State);
}
///
/// throw exception if POP3 connection is not in the required state
///
///
protected void EnsureState(Pop3ConnectionStateEnum requiredState) {
if (pop3ConnectionState!=requiredState) {
// wrong connection state
throw new Pop3Exception("GetMailboxStats only accepted during connection state: " + requiredState.ToString() +
"\n The connection to server "+ popServer + " is in state " + pop3ConnectionState.ToString());
}
}
//private fields
//--------------
///
/// TCP to POP3 server
///
private TcpClient serverTcpConnection;
///
/// Stream from POP3 server with or without SSL
///
private Stream pop3Stream;
///
/// Reader for POP3 message
///
protected StreamReader pop3StreamReader;
///
/// char 'array' for carriage return / line feed
///
protected string CRLF = "\r\n";
//public methods
//--------------
///
/// Make POP3 client ready to connect to POP3 server
///
///
///
/// True: SSL is used for connection to POP3 server
///
/// Secret
public Pop3MailClient(string PopServer, int Port, bool useSSL, string Username, string Password) {
this.popServer = PopServer;
this.port = Port;
this.useSSL = useSSL;
this.username = Username;
this.password = Password;
}
///
/// Connect to POP3 server
///
public void Connect() {
if (pop3ConnectionState!=Pop3ConnectionStateEnum.Disconnected &&
pop3ConnectionState!=Pop3ConnectionStateEnum.Closed &&
!isTimeoutReconnect) {
CallWarning("connect", "", "Connect command received, but connection state is: " + pop3ConnectionState.ToString());
} else {
//establish TCP connection
try {
CallTrace(" Connect at port {0}", port);
serverTcpConnection = new TcpClient(popServer, port);
} catch (Exception ex) {
throw new Pop3Exception("Connection to server "+ popServer + ", port " + port + " failed.\nRuntime Error: "+ex.ToString());
}
if (useSSL) {
//get SSL stream
try {
CallTrace(" Get SSL connection");
pop3Stream = new SslStream(serverTcpConnection.GetStream(), false);
pop3Stream.ReadTimeout = readTimeout;
} catch (Exception ex) {
throw new Pop3Exception("Server " + popServer + " found, but cannot get SSL data stream.\nRuntime Error: "+ex.ToString());
}
//perform SSL authentication
try {
CallTrace(" Get SSL authentication");
((SslStream)pop3Stream).AuthenticateAsClient(popServer);
} catch (Exception ex) {
throw new Pop3Exception("Server " + popServer + " found, but problem with SSL Authentication.\nRuntime Error: " + ex.ToString());
}
} else {
//create a stream to POP3 server without using SSL
try {
CallTrace(" Get connection without SSL");
pop3Stream = serverTcpConnection.GetStream();
pop3Stream.ReadTimeout = readTimeout;
} catch (Exception ex) {
throw new Pop3Exception("Server " + popServer + " found, but cannot get data stream (without SSL).\nRuntime Error: "+ex.ToString());
}
}
//get stream for reading from pop server
//POP3 allows only US-ASCII. The message will be translated in the proper encoding in a later step
try {
pop3StreamReader= new StreamReader(pop3Stream, Encoding.ASCII);
} catch (Exception ex) {
if (useSSL) {
throw new Pop3Exception("Server " + popServer + " found, but cannot read from SSL stream.\nRuntime Error: " + ex.ToString());
} else {
throw new Pop3Exception("Server " + popServer + " found, but cannot read from stream (without SSL).\nRuntime Error: " + ex.ToString());
}
}
//ready for authorisation
string response;
if (!readSingleLine(out response)) {
throw new Pop3Exception("Server " + popServer + " not ready to start AUTHORIZATION.\nMessage: " + response);
}
setPop3ConnectionState(Pop3ConnectionStateEnum.Authorization);
//send user name
if (!executeCommand("USER "+ username, out response)) {
throw new Pop3Exception("Server " + popServer + " doesn't accept username '" + username + "'.\nMessage: " + response);
}
//send password
if (!executeCommand("PASS " + password, out response)) {
throw new Pop3Exception("Server " + popServer + " doesn't accept password '" + password + "' for user '" + username + "'.\nMessage: " + response);
}
setPop3ConnectionState(Pop3ConnectionStateEnum.Connected);
}
}
///
/// Disconnect from POP3 Server
///
public void Disconnect() {
if (pop3ConnectionState==Pop3ConnectionStateEnum.Disconnected ||
pop3ConnectionState==Pop3ConnectionStateEnum.Closed) {
CallWarning("disconnect", "", "Disconnect received, but was already disconnected.");
} else {
//ask server to end session and possibly to remove emails marked for deletion
try {
string response;
if (executeCommand("QUIT", out response)) {
//server says everything is ok
setPop3ConnectionState(Pop3ConnectionStateEnum.Closed);
} else {
//server says there is a problem
CallWarning("Disconnect", response, "negative response from server while closing connection: " + response);
setPop3ConnectionState(Pop3ConnectionStateEnum.Disconnected);
}
} finally {
//close connection
if (pop3Stream!=null) {
pop3Stream.Close();
}
pop3StreamReader.Close();
}
}
}
///
/// Delete message from server.
/// The POP3 server marks the message as deleted. Any future
/// reference to the message-number associated with the message
/// in a POP3 command generates an error. The POP3 server does
/// not actually delete the message until the POP3 session
/// enters the UPDATE state.
///
///
///
public bool DeleteEmail(int msg_number) {
EnsureState(Pop3ConnectionStateEnum.Connected);
string response;
if (!executeCommand("DELE " + msg_number.ToString(), out response)) {
CallWarning("DeleteEmail", response, "negative response for email (Id: {0}) delete request", msg_number);
return false;
}
return true;
}
///
/// Get a list of all Email IDs available in mailbox
///
///
public bool GetEmailIdList(out List
EnsureState(Pop3ConnectionStateEnum.Connected);
EmailIds = new List
//get server response status line
string response;
if (!executeCommand("LIST", out response)) {
CallWarning("GetEmailIdList", response, "negative response for email list request");
return false;
}
//get every email id
int EmailId;
while (readMultiLine(out response)) {
if (int.TryParse(response.Split(' ')[0], out EmailId)) {
EmailIds.Add(EmailId);
} else {
CallWarning("GetEmailIdList", response, "first characters should be integer (EmailId)");
}
}
TraceFrom("{0} email ids received", EmailIds.Count);
return true;
}
///
/// get size of one particular email
///
///
///
public int GetEmailSize(int msg_number) {
EnsureState(Pop3ConnectionStateEnum.Connected);
string response;
executeCommand("LIST " + msg_number.ToString(), out response);
int EmailSize = 0;
string[] responseSplit = response.Split(' ');
if (responseSplit.Length<2>
/// Get a list with the unique IDs of all Email available in mailbox.
///
/// Explanation:
/// EmailIds for the same email can change between sessions, whereas the unique Email id
/// never changes for an email.
///
///
///
public bool GetUniqueEmailIdList(out List
EnsureState(Pop3ConnectionStateEnum.Connected);
EmailIds = new List
//get server response status line
string response;
if (!executeCommand("UIDL ", out response)) {
CallWarning("GetUniqueEmailIdList", response, "negative response for email list request");
return false;
}
//get every email unique id
int EmailId;
while (readMultiLine(out response)) {
string[] responseSplit = response.Split(' ');
if (responseSplit.Length<2)>
/// get a list with all currently available messages and the UIDs
///
/// EmailId Uid list
///
public bool GetUniqueEmailIdList(out SortedList
EnsureState(Pop3ConnectionStateEnum.Connected);
EmailIds = new SortedList
//get server response status line
string response;
if (!executeCommand("UIDL", out response)) {
CallWarning("GetUniqueEmailIdList", response, "negative response for email list request");
return false;
}
//get every email unique id
int EmailId;
while (readMultiLine(out response)) {
string[] responseSplit = response.Split(' ');
if (responseSplit.Length<2)>
/// get size of one particular email
///
///
///
public int GetUniqueEmailId(EmailUid msg_number) {
EnsureState(Pop3ConnectionStateEnum.Connected);
string response;
executeCommand("LIST " + msg_number.ToString(), out response);
int EmailSize = 0;
string[] responseSplit = response.Split(' ');
if (responseSplit.Length<2>
/// Sends an 'empty' command to the POP3 server. Server has to respond with +OK
///
///
public bool NOOP() {
EnsureState(Pop3ConnectionStateEnum.Connected);
string response;
if (!executeCommand("NOOP", out response)) {
CallWarning("NOOP", response, "negative response for NOOP request");
return false;
}
return true;
}
///
/// Should the raw content, the US-ASCII code as received, be traced
/// GetRawEmail will switch it on when it starts and off once finished
///
/// Inheritors might use it to get the raw email
///
protected bool isTraceRawEmail = false;
///
/// contains one MIME part of the email in US-ASCII, needs to be translated in .NET string (Unicode)
/// contains the complete email in US-ASCII, needs to be translated in .NET string (Unicode)
/// For speed reasons, reuse StringBuilder
///
protected StringBuilder RawEmailSB;
///
/// Reads the complete text of a message
///
/// Email to retrieve
/// ASCII string of complete message
///
public bool GetRawEmail(int MessageNo, out string EmailText) {
//send 'RETR int' command to server
if (!SendRetrCommand(MessageNo)) {
EmailText = null;
return false;
}
//get the lines
string response;
int LineCounter = 0;
//empty StringBuilder
if (RawEmailSB==null) {
RawEmailSB = new StringBuilder(100000);
} else {
RawEmailSB.Length = 0;
}
isTraceRawEmail = true;
while (readMultiLine(out response)) {
LineCounter += 1;
}
EmailText = RawEmailSB.ToString();
TraceFrom("email with {0} lines, {1} chars received", LineCounter.ToString(), EmailText.Length);
return true;
}
/////
///// Requests from POP3 server a specific email and returns a stream with the message content (header and body)
/////
/////
/////
/////
//public bool GetEmailStream(int MessageNo, out StreamReader EmailStreamReader) {
// //send 'RETR int' command to server
// if (!SendRetrCommand(MessageNo)) {
// EmailStreamReader = null;
// return false;
// }
// EmailStreamReader = sslStreamReader;
// return true;
//}
///
/// Unmark any emails from deletion. The server only deletes email really
/// once the connection is properly closed.
///
///
public bool UndeleteAllEmails() {
EnsureState(Pop3ConnectionStateEnum.Connected);
string response;
return executeCommand("RSET", out response);
}
///
/// Get mailbox statistics
///
///
///
///
public bool GetMailboxStats(out int NumberOfMails, out int MailboxSize) {
EnsureState(Pop3ConnectionStateEnum.Connected);
//interpret response
string response;
NumberOfMails = 0;
MailboxSize =0;
if (executeCommand("STAT", out response)) {
//got a positive response
string[] responseParts = response.Split(' ');
if (responseParts.Length<2) numberofmails =" int.Parse(responseParts[1]);" mailboxsize =" int.Parse(responseParts[2]);">
/// Send RETR command to POP 3 server to fetch one particular message
///
/// ID of message required
///
protected bool SendRetrCommand(int MessageNo) {
EnsureState(Pop3ConnectionStateEnum.Connected);
// retrieve mail with message number
string response;
if (!executeCommand("RETR "+ MessageNo.ToString(), out response)) {
CallWarning("GetRawEmail", response, "negative response for email (ID: {0}) request", MessageNo);
return false;
}
return true;
}
//Helper methodes
//---------------
///
/// sends the 4 letter command to POP3 server (adds CRLF) and waits for the
/// response of the server
///
/// command to be sent to server
/// answer from server
///
public bool isDebug = false;
private bool executeCommand(string command, out string response) {
//send command to server
byte[] commandBytes = System.Text.Encoding.ASCII.GetBytes((command + CRLF).ToCharArray());
CallTrace("Tx '{0}'", command);
bool isSupressThrow = false;
try {
pop3Stream.Write(commandBytes, 0, commandBytes.Length);
if (isDebug) {
isDebug=false;
throw new IOException("Test", new SocketException(10053));
}
} catch (IOException ex) {
//Unable to write data to the transport connection. Check if reconnection should be tried
isSupressThrow = executeReconnect(ex, command, commandBytes);
if (!isSupressThrow) {
throw;
}
}
pop3Stream.Flush();
//read response from server
response = null;
try {
response = pop3StreamReader.ReadLine();
} catch (IOException ex) {
//Unable to write data to the transport connection. Check if reconnection should be tried
isSupressThrow = executeReconnect(ex, command, commandBytes);
if (isSupressThrow) {
//wait for response one more time
response = pop3StreamReader.ReadLine();
} else {
throw;
}
}
if (response==null) {
throw new Pop3Exception("Server "+ popServer + " has not responded, timeout has occured.");
}
CallTrace("Rx '{0}'", response);
return (response.Length>0 && response[0]=='+');
}
///
/// reconnect, if there is a timeout exception and isAutoReconnect is true
///
///
private bool executeReconnect(IOException ex, string command, byte[] commandBytes) {
if (ex.InnerException!=null && ex.InnerException is SocketException) {
//SocketException
SocketException innerEx = (SocketException)ex.InnerException;
if (innerEx.ErrorCode==10053) {
//probably timeout: An established connection was aborted by the software in your host machine.
CallWarning("ExecuteCommand", "", "probably timeout occured");
if (isAutoReconnect) {
//try to reconnect and send one more time
isTimeoutReconnect = true;
try {
CallTrace(" try to auto reconnect");
Connect();
CallTrace(" reconnect successful, try to resend command");
CallTrace("Tx '{0}'", command);
pop3Stream.Write(commandBytes, 0, commandBytes.Length);
pop3Stream.Flush();
return true;
} finally {
isTimeoutReconnect = false;
}
}
}
}
return false;
}
/*
///
/// sends the 4 letter command to POP3 server (adds CRLF)
///
///
protected void SendCommand(string command) {
byte[] commandBytes = System.Text.Encoding.ASCII.GetBytes((command + CRLF).ToCharArray());
CallTrace("Tx '{0}'", command);
try {
pop3Stream.Write(commandBytes, 0, commandBytes.Length);
} catch (IOException ex) {
//Unable to write data to the transport connection:
if (ex.InnerException!=null && ex.InnerException is SocketException) {
//SocketException
SocketException innerEx = (SocketException)ex.InnerException;
if (innerEx.ErrorCode==10053) {
//probably timeout: An established connection was aborted by the software in your host machine.
CallWarning("SendCommand", "", "probably timeout occured");
if (isAutoReconnect) {
//try to reconnect and send one more time
isTimeoutReconnect = true;
try {
CallTrace(" try to auto reconnect");
Connect();
CallTrace(" reconnect successful, try to resend command");
CallTrace("Tx '{0}'", command);
pop3Stream.Write(commandBytes, 0, commandBytes.Length);
} finally {
isTimeoutReconnect = false;
}
return;
}
}
}
throw;
}
pop3Stream.Flush();
}
*/
///
/// read single line response from POP3 server.
///
///
/// response from POP3 server
///
protected bool readSingleLine(out string response) {
response = null;
try {
response = pop3StreamReader.ReadLine();
} catch (Exception ex) {
string s = ex.Message;
}
if (response==null) {
throw new Pop3Exception("Server "+ popServer + " has not responded, timeout has occured.");
}
CallTrace("Rx '{0}'", response);
return (response.Length>0 && response[0]=='+');
}
///
/// read one line in multiline mode from the POP3 server.
///
/// line received
///
///
protected bool readMultiLine(out string response) {
response = null;
response = pop3StreamReader.ReadLine();
if (response==null) {
throw new Pop3Exception("Server "+ popServer + " has not responded, probably timeout has occured.");
}
if (isTraceRawEmail) {
//collect all responses as received
RawEmailSB.Append(response + CRLF);
}
//check for byte stuffing, i.e. if a line starts with a '.', another '.' is added, unless
//it is the last line
if (response.Length>0 && response[0]=='.') {
if (response==".") {
//closing line found
return false;
}
//remove the first '.'
response = response.Substring(1, response.Length-1);
}
return true;
}
}
Suscribirse a:
Entradas (Atom)