I have to implement IMAP to use it in my own email client via C# and .NET Standard 2.0. During the task, I can use TcpClient and SslStream classes. The problem lies in getting response from the server. I can't find a common solution how to identify the end of the message. Such as SMTP has "\r\n.\r\n" in the end of each message, IMAP has no the same pattern (according to my research). The majority of IMAP messages ends with [TAG] [RESPONSE]
, for example A1 OK success
, but there are some which ends with * OK Gimap...
or * BAD Invalid...
. I just wrote a few lines of code:
class Program
{
static TcpClient tcp;
static SslStream ssl;
static void Main(string[] args)
{
tcp = new TcpClient("imap.gmail.com", 993);
ssl = new SslStream(tcp.GetStream());
ssl.AuthenticateAsClient("imap.gmail.com");
ReceiveResponse("");
while (true)
{
try
{
string query = Console.ReadLine();
if (query == "exit") break;
ReceiveResponse(query + "\r\n");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Console.WriteLine(ReceiveResponse("$ LOGOUT\r\n"));
Console.ReadKey();
}
static string ReceiveResponse(string query)
{
StringBuilder sb = new StringBuilder();
try
{
if (query != "")
{
if (tcp.Connected)
{
byte[] dummy = Encoding.ASCII.GetBytes(query);
ssl.Write(dummy, 0, dummy.Length);
}
else
{
throw new ApplicationException("TCP CONNECTION DISCONNECTED!!");
}
}
ssl.Flush();
byte[] buffer = new byte[1024];
List<byte> response = new List<byte>();
while (true) // ваш метод, который определит полный ответ
{
int bytesRead = ssl.Read(buffer, 0, 1024);
if (bytesRead == 0)
throw new EndOfStreamException("err");
string str = Encoding.UTF8.GetString(buffer).Replace("\0", "");
sb.Append(str);
if (/* PATTERN I NEED*/) break;
}
Console.WriteLine(sb.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return sb.ToString();
}
}
As you understand, I need the pattern to identify the univocal end of the message or at least solution how to get full message from IMAP server.
P.S. I'm not English native speaker, and it would be nice if you could express your thougth in simple words. Thanks in advance.