csharp
namespace EmailSoftWare.Models.EmailClients
{
public class ImapClient
{
private TcpClient _client;
private StreamReader _reader;
private StreamWriter _writer;
private SslStream _sslStream;
private Account _account;
private ProxyType _proxyType;
private string _response = "";
private IPAddress _ipAddress;
private int _currentTagNumber = 0;
private string _currentRequest = "";
public ImapClient(Account account, ProxyType proxyType)
{
_account = account;
_proxyType = proxyType;
}
private string GenerateTag()
{
_currentTagNumber++;
return $"A{_currentTagNumber:000}";
}
private bool ConnectProxy(ProxyType proxyType, byte[] buffer)
{
switch (proxyType)
{
case ProxyType.Socks4:
_client = new Socks4Client().GetClient();
break;
case ProxyType.Socks5:
_client = new Socks5Client().GetClient();
break;
case ProxyType.Https:
_client = new HTTPsClient().GetClient();
break;
case ProxyType.None:
_client = new TcpClient();
break;
}
_client.ReceiveTimeout = Connections.ViewManager.TimeOut;
_client.SendTimeout = Connections.ViewManager.TimeOut;
_reader = new StreamReader(_client.GetStream(), Encoding.ASCII);
_writer = new StreamWriter(_client.GetStream(), Encoding.ASCII);
if (proxyType == ProxyType.Socks4 || proxyType == ProxyType.Socks5)
{
_writer.BaseStream.Write(buffer, 0, 8 + 4);
_reader.BaseStream.Read(buffer, 0, 8);
if (buffer[1] != 90)
{
_client?.Dispose();
return false;
}
}
else if (proxyType == ProxyType.Https)
{
SendCommand($"CONNECT {_ipAddress}:{_account.Port} HTTP/1.1\r\nHost: {_ipAddress}:{_account.Port}\r\n\r\n");
string connectResponse = ReadResponse();
if (!connectResponse.Contains("200"))
{
_client?.Dispose();
return false;
}
}
return true;
}
private void ConnectWithoutProxy()
{
_client = new TcpClient();
_client.ReceiveTimeout = Connections.ViewManager.TimeOut;
_client.SendTimeout = Connections.ViewManager.TimeOut;
_client.Connect(_ipAddress, _account.Port);
_reader = new StreamReader(_client.GetStream(), Encoding.ASCII);
_writer = new StreamWriter(_client.GetStream(), Encoding.ASCII);
}
private void ConnectSecurely()
{
_sslStream = new SslStream(_client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
_sslStream.AuthenticateAsClient(_ipAddress.ToString());
_reader = new StreamReader(_sslStream, Encoding.ASCII);
_writer = new StreamWriter(_sslStream, Encoding.ASCII);
}
private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
// Add your custom certificate validation logic here
return true;
}
private void CheckResponse(string response)
{
if (response == null || !response.Contains("OK", StringComparison.OrdinalIgnoreCase))
{
throw new Exception();
}
}
private void WriteEmailToFile(string path, string email)
{
lock (Connections.ViewManager.LockerWriteLetters)
{
File.AppendAllText(path, $"{_account.FullData}\n");
}
}
private void DownloadLetters(string directoryPath, string request, List<Email> emails)
{
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
foreach (var item in emails)
{
if (item.From.Contains(request, StringComparison.OrdinalIgnoreCase))
{
string filePath = Path.Combine(directoryPath, _account.Email + ".html");
File.AppendAllText(filePath, $"<center>===================================================<br>\r\nAccount: {_account.FullData}<br>\r\nSubject: {item.Subject}<br>\r\nFrom: {item.From.Replace("<", "").Replace(">", "")}<br>\r\nDate: {item.Date}<br><br>\r\n\r\n</center>{item.Body}<center><br>\r\n===================================================<br>\r\n</center>");
}
}
}
private void ProcessRequest(string request)
{
var emails = SearchEmailsBySenderInAllMailboxes(request);
if (emails.Any(x => x.From.Contains(request, StringComparison.OrdinalIgnoreCase)))
{
string filePath = Path.Combine(Connections.ViewManager.MainWindow.PathToSaveResults, request + ".txt");
WriteEmailToFile(filePath, $"{_account.FullData}\n");
}
if (Connections.ViewManager.DownloadLetters)
{
string directoryPath = Path.Combine(Connections.ViewManager.MainWindow.PathToSaveResults, request);
DownloadLetters(directoryPath, request, emails);
}
}
public void Connect()
{
while (true)
{
try
{
byte[] buffer;
_ipAddress = IPAddress.Parse(GetIpAddress(_account.Server));
_currentTagNumber = 0;
switch (_proxyType)
{
case ProxyType.Socks4:
case ProxyType.Socks5:
buffer = new byte[4096];
buffer[0] = (byte)(_proxyType == ProxyType.Socks5 ? 5 : 4);
buffer[1] = 1;
buffer[2] = (byte)(_account.Port >> 8);
buffer[3] = (byte)(_account.Port & 0xFF);
Array.Copy(_ipAddress.GetAddressBytes(), 0, buffer, 4, 4);
if (!ConnectProxy(_proxyType, buffer))
{
continue;
}
break;
case ProxyType.Https:
buffer = new byte[4096];
buffer[0] = 5;
buffer[1] = 1;
buffer[2] = 0;
buffer[3] = 1;
Array.Copy(_ipAddress.GetAddressBytes(), 0, buffer, 4, 4);
buffer[8] = (byte)(_account.Port / 256);
buffer[9] = (byte)(_account.Port % 256);
if (!ConnectProxy(_proxyType, buffer))
{
continue;
}
break;
case ProxyType.None:
ConnectWithoutProxy();
break;
}
if (_account.Port == 993)
{
ConnectSecurely();
}
if (_account.Port != 143 && _proxyType != ProxyType.Https)
{
_response = ReadResponse();
CheckResponse(_response);
}
SendCommand($"{GenerateTag()} LOGIN \"{_account.Email}\" \"{_account.Password}\"\r\n");
_response = ReadResponse();
_account.Result = ServerResponseParser.AnswerHandler(_response.ToLower());
if (_account.Result == Result.ToCheck)
{
_account.Result = Result.Bad;
_client?.Dispose();
return;
}
else if (_account.Result == Result.Error)
{
_client?.Dispose();
throw new Exception();
}
if (_account.Result == Result.Good)
{
if (Connections.ViewManager.SearchForEmails)
{
foreach (var request in Connections.ViewManager.ReqList)
{
ProcessRequest(request);
}
}
_client?.Dispose();
return;
}
_client?.Dispose();
return;
}
catch (Exception e)
{
_client?.Dispose();
if (e is SocketException)
{
_account.Result = Result.WrongServer;
return;
}
if (_account.Errors > 30)
{
_account.Result = Result.Error;
return;
}
_account.Errors++;
}
}
}
}
}