I'm getting email with attachments by simple IMAP client:
class Program
{
static StreamWriter sw = null;
static TcpClient tcpc = null;
static SslStream ssl = null;
static string path;
static StringBuilder sb = new StringBuilder();
static byte[] dummy;
string username = "user";
string password = "pass";
static void Main(string[] args)
{
try
{
path = Environment.CurrentDirectory + "\\emailresponse.txt";
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
using (sw = new System.IO.StreamWriter(System.IO.File.Create(path)))
using (tcpc = new System.Net.Sockets.TcpClient("imap.server.com", 993))
using (ssl = new System.Net.Security.SslStream(tcpc.GetStream()))
{
ssl.AuthenticateAsClient("imap.server.com");
receiveResponse("");
receiveResponse("$ LOGIN " + username + " " + password + "\r\n");
Console.WriteLine("enter the email number to fetch :");
int number = int.Parse(Console.ReadLine());
receiveResponse("$ FETCH " + number + " body[header]\r\n");
receiveResponse("$ FETCH " + number + " body[text]\r\n");
receiveResponse("$ LOGOUT\r\n");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
static void receiveResponse(string command)
{
try
{
if (command != "")
{
if (tcpc.Connected)
{
dummy = Encoding.Default.GetBytes(command);
ssl.Write(dummy, 0, dummy.Length);
}
else
{
throw new ApplicationException("TCP CONNECTION DISCONNECTED");
}
}
ssl.Flush();
byte[] bigBuffer = new byte[1024*18];
int bites = ssl.Read(bigBuffer, 0, bigBuffer.Length);
byte[] buffer = new byte[bites];
Array.Copy(bigBuffer, 0, buffer, 0, bites);
sb.Append(Encoding.Default.GetString(buffer));
sw.WriteLine(sb.ToString());
sb = new StringBuilder();
}
catch (Exception ex)
{
throw new ApplicationException(ex.ToString());
}
}
}
Everything is alright, but if email size is more than ~19kb, content is cropped regardless of buffer size. How to fix it?
Solution is that I have to repeat request receiveResponse("$ FETCH " + number + " body[text]\r\n")
till I get all data pieces. And problem was that I did loop inside receiveResponse
instead of main block.