Checking emails exist , auto-reconnect tcpclient c# - c#

I'm trying to create a app checking email exist using .NET
I was thinking for 2 hours didn't figure any solution
the purpose of this solution is make my server dodging the ban or exceed of test.
my problem is how to auto-reconnect the TcpClient after number of email checked and continuing from last email in the Array
public void isChecked(string[] MailCheck,string length)
{
//converte ArrayLength from string to int
int num = int.Parse(length);
TcpClient tClient = new TcpClient("smtp-in.orange.fr", 25);
string CRLF = "\r\n";
byte[] dataBuffer;
string ResponseString;
NetworkStream netStream = tClient.GetStream();
StreamReader reader = new StreamReader(netStream);
ResponseString = reader.ReadLine();
/* Perform HELO to SMTP Server and get Response */
dataBuffer = BytesFromString("HELO Contact" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
dataBuffer = BytesFromString("mail from:<contact#contact.com>" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
for (i = 0; i < num; i++)
{
/* Read Response of the RCPT TO Message to know from google if it exist or not */
dataBuffer = BytesFromString("rcpt to:<" + MailCheck[i] + ">" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
if (GetResponseCode(ResponseString) == 550)
{
//MessageBox.Show("false " + ResponseString);
System.Diagnostics.Debug.WriteLine("false || " + ResponseString);
}
else
{
//MessageBox.Show("true " + ResponseString);
System.Diagnostics.Debug.WriteLine("true || " + ResponseString);
System.IO.File.AppendAllText(#"C:/WarningsLog.txt", MailCheck[i] + Environment.NewLine);
}
}

You could
put the recipients into a List
as outer loop, iterate while the list is not empty. To avoid an endless loop, you may consider to limit the number of iterations.
connect to the SMPT server
as inner loop, send the messages. When a mail could be sent, remove the recipient from the list. If a transient error occured, exit the inner loop
Did you consider using an existing SMTP client implementation like https://github.com/jstedfast/MailKit or at least System.Net.SmtpClient?

Related

Cannot read data from HttpListener .NET

I am stuck with reading data from HttpListener. Data arrives, I verify it with request.ContentLength64 that is usually over 8000 and it increases as the server generates more and more data.
The server sends data as HTTP post and the content type is text/plain.
When I try to check whether streamreader got some data via its length attribute I get 0.
The code is a little bit messy as I was trying different ways to make it work but unfortunatelly I had no luck.
Does anyone got an idea what I'm doing wrong?
Thanks!
HttpListener listener2 = new HttpListener();
listener2.Prefixes.Clear();
listener2.Prefixes.Add("http://+:4200/");
listener2.Prefixes.Add("http://XXX.XXX.eu/");
listener2.Start();
LogWriteLine("http listener started listening to: " +listener2.Prefixes);
try
{
while (true)//change to match end check
{
LogWriteLine("http listener waiting");
HttpListenerContext context = listener2.GetContext();
LogWriteLine("http request arrived");
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
if (!request.HasEntityBody)
{
LogWriteLine("No client data was sent with the request.");
Thread.Sleep(300);
//return;
}
if (request.ContentType != null)
{
LogWriteLine("Client data content type " + request.ContentType);
}
LogWriteLine("Client data content length " + request.ContentLength64); //Works fine
LogWriteLine("Start of client data:");
// Convert the data to a string and display it on the console.
Console.WriteLine(body.CanSeek);
string s = reader.ReadToEnd();
var ahoj = new StreamReader(context.Request.InputStream).ReadToEnd();
Console.WriteLine("ahoj length " + ahoj.Length); //0
Console.WriteLine(s); //nothing
string text;
var bytes = default(byte[]);
using (var reader1 = new StreamReader(request.InputStream,
request.ContentEncoding))
{
text = reader1.ReadToEnd();
Console.WriteLine(text + text.Length); //output: 0
using (var memstream = new MemoryStream())
{
reader1.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
}
Console.WriteLine("bytes:" + bytes.Length); //output: bytes: 0
}
LogWriteLine("End of client data:");
//write to console file
sw.Write(s);
body.Close();
reader.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}

Resuming interrupted upload using Google drive v3 C# sdk

I want to resume interrupted resumable upload using Google Drive v3 C# SDK.
The reason why I want this is to create resumable upload in Restful Web API.
There is google drive api instance in this RestAPI, so this is relaying chunk data from client program to google drive.
As you know, client program cannot upload whole file data at one time to Web API, so we need to resume interrupted resumable upload.
So my plan is here.
First, we need to create upload session and receive Session URI.
Second, Create Upload instance every time from returned URI and add chunk data.
Third, repeat 2nd process until EOF.
For this, I made test code, but it does not work at all.
var uploadStream = new System.IO.FileStream(UploadFileName, System.IO.FileMode.Open,
System.IO.FileAccess.Read);
var insert = service.Files.Create(new Google.Apis.Drive.v3.Data.File { Name = title }, uploadStream, ContentType);
Uri uploadUri = insert.InitiateSessionAsync().Result;
int chunk_size = ResumableUpload.MinimumChunkSize;
while (uploadStream.Length != uploadStream.Position)
{
byte[] temp = new byte[chunk_size];
uploadStream.Read(temp, 0, temp.Length);
MemoryStream stream = new MemoryStream(temp);
ResumableUpload resume_uploader = ResumableUpload.CreateFromUploadUri(uploadUri, stream);
resume_uploader.ChunkSize = chunk_size;
IUploadProgress ss = resume_uploader.Resume();
Console.WriteLine("Uploaded " + ss.BytesSent.ToString());
}
Frankly, I expected to receive 308 Resume Incomplete Code, but the result is different.
"Invalid request. According to the Content-Range header, the final size of the upload is 262144 byte(s). This does not match the expected size of 1193188 byte(s), which was specified in an earlier request."
This means that I need to create code that resumes interrupted resumable upload using Google Drive C# SDK.
Anybody can help me?
Finally, I solved issue. Exact code is below. Actually, I could not find any source code on Google, so I was so sad. Every developer who wants to solve this issue, use my code please. Hope you are fine. :)
public static async Task<Google.Apis.Drive.v3.Data.File> UploadSync(DriveService driveService, string filepath)
{
string destfilename = Path.GetFileName(filepath);
List<string> parents = new List<string>();
parents.Add("root");
// Prepare the JSON metadata
string json = "{\"name\":\"" + destfilename + "\"";
if (parents.Count > 0)
{
json += ", \"parents\": [";
foreach (string parent in parents)
{
json += "\"" + parent + "\", ";
}
json = json.Remove(json.Length - 2) + "]";
}
json += "}";
Debug.WriteLine(json);
Google.Apis.Drive.v3.Data.File uploadedFile = null;
try
{
System.IO.FileInfo info = new System.IO.FileInfo(filepath);
ulong fileSize = (ulong)info.Length;
var uploadStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
var insert = driveService.Files.Create(new Google.Apis.Drive.v3.Data.File { Name = destfilename, Parents = new List<string> { "root" } }, uploadStream, "application/octet-stream");
Uri uploadUri = insert.InitiateSessionAsync().Result;
int chunk_size = ResumableUpload.MinimumChunkSize;
int bytesSent = 0;
while (uploadStream.Length != uploadStream.Position)
{
byte[] temp = new byte[chunk_size];
int cnt = uploadStream.Read(temp, 0, temp.Length);
if (cnt == 0)
break;
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uploadUri);
httpRequest.Method = "PUT";
httpRequest.Headers["Authorization"] = "Bearer " + ((UserCredential)driveService.HttpClientInitializer).Token.AccessToken;
httpRequest.ContentLength = (long)cnt;
httpRequest.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", bytesSent, bytesSent + cnt - 1, fileSize);
using (System.IO.Stream requestStream = httpRequest.GetRequestStreamAsync().Result)
{
requestStream.Write(temp, 0, cnt);
}
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
if (httpResponse.StatusCode == HttpStatusCode.OK)
{ }
else if ((int)httpResponse.StatusCode != 308)
break;
bytesSent += cnt;
Console.WriteLine("Uploaded " + bytesSent.ToString());
}
if (bytesSent != uploadStream.Length)
{
return null;
}
// Try to retrieve the file from Google
FilesResource.ListRequest request = driveService.Files.List();
if (parents.Count > 0)
request.Q += "'" + parents[0] + "' in parents and ";
request.Q += "name = '" + destfilename + "'";
FileList result = request.Execute();
if (result.Files.Count > 0)
uploadedFile = result.Files[0];
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return uploadedFile;
}

Http Get Request for IpDBInfo using an IP Address

I am working on a web application and it needs to track a location using an IP Address and I am new to sending requests to some APIs and getting a response from them. I was able to retrieve IP address of the user using Request.UserHostAddress
and was able to validate it using the following C# code
if (System.Text.RegularExpressions.Regex.IsMatch(ip, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
{
string[] ips = ip.Split('.');
if (ips.Length == 4 || ips.Length == 6)
{
if (System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256
& System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256)
return true;
else
return false;
}
else
return false;
}
else
return false;
and I have got the API key and IP address required to request the following API
http://api.ipinfodb.com/v2/ip_query.php?key=[API KEY]&ip=[IP Address]&timezone=false
I know an HTTP GET REQUEST to the above would give me an XML response but not sure how to get started with the HTTP REQUEST in ASP.NET MVC using C#.
Can someone help me get started with this?
The response of IPInfoDB is a string like below:
OK;;74.125.45.100;US;United States;California;Mountain
View;94043;37.406;-122.079;-07:00
So we need to split into the various fields using C# codes below.
string key = "Your API key";
string ip = "IP address to check";
string url = "http://api.ipinfodb.com/v3/ip-city/?key=" + key + "&ip=" + ip;
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(string.Format(url));
webReq.Method = "GET";
HttpWebResponse webResponse = (HttpWebResponse)webReq.GetResponse();
Stream answer = webResponse.GetResponseStream();
StreamReader response = new StreamReader(answer);
string raw = response.ReadToEnd();
char[] delimiter = new char[1];
delimiter[0] = ';';
string[] rawdata = raw.Split(delimiter);
ViewData["Response"] = "Country Code: " + rawdata[3] + " Country Name: " + rawdata[4] + " State: " + rawdata[5] + " City: " + rawdata[6];
response.Close();

TCP Client not receiving response on loopback

I've got a TCP server up and running on localhost on vs2010 on windows 2k8.
When I connect the client on 127.0.0.1 using vs2010, the server gets the call, (I can see it
from debug) as the tcp server executes the command line protocol handler, but the client does
recieve the server response, which is the session key, but blocks at the client when reading
the respone stream.
When I use Telnet on loopback for the same port, sending the same command sequence, the
response, i.e. the session key, is received instantaneously.
Here is the client code:
EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9121);
sing (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect(serverAddress);
var socketStream = new NetworkStream(socket);
var reader = new StreamReader(socketStream, Encoding.ASCII, false);
var writer = new StreamWriter(socketStream, Encoding.ASCII, 1024);
string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
+ Guid.NewGuid().ToString().Replace("-", string.Empty)
+ Guid.NewGuid().ToString().Replace("-", string.Empty);
Random rd = new Random();
int startPos = rd.Next(0, charSource.Length - 2);
int endPos = rd.Next(startPos + 1, charSource.Length - 1);
var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);
Console.WriteLine("Sent Command");
writer.Write("HEAR {0} {1}", currentMessage.Length.ToString().PadLeft(4, '0'), currentMessage);
writer.Flush();
Console.WriteLine("Reading Command Results");
var line = reader.ReadLine();
Console.WriteLine("Received: " + line);
}
Bob
To make this work, please change Write with WriteLine as shown in the code below:
Console.WriteLine("Sent Command");
writer.WriteLine("HEAR {0} {1}", currentMessage.Length.ToString().PadLeft(4, '0'), currentMessage);
writer.Flush();
Enable network tracing, so you can be sure that the data is comming. It probably is, so change your call to reader.Read and read until you find the end of the message.

IMAP Response not proper

I am working on C# MailClient and which is follow IMAP Protocol, but I am getting wrong response that means the response will give me some repetitive resul.
Like say first time I am sending command like this.
byte[] commandBytes = System.Text.Encoding.ASCII.GetBytes(("$ UID FETCH " + index + " (BODY[HEADER.FIELDS (SUBJECT FROM DATE)])\r\n"));
and second time I am sending like this.
byte[] commandBytes = System.Text.Encoding.ASCII.GetBytes(("$ UID FETCH " + index + " (BODYSTRUCTURE)" + "\r\n"));
so I am getting again first command result in twice or more than 2 times;
and some times it's continue giving me first result.
my Response() method is like this.
private string Response()
{
string response = string.Empty;
byte[] data = new byte[_imapClient.ReceiveBufferSize];
int ret = _imapNs.Read(data, 0, data.Length);
response = Encoding.ASCII.GetString(data,0,ret);
return response;
}
_imapClient is a object of an
private TcpClient _imapClient;
and I am taking value of _imapClient is like this.
public string GetMessageBodyStructure(int index)
{
byte[] commandBytes = System.Text.Encoding.ASCII.GetBytes(("$ UID FETCH " + index + " (BODYSTRUCTURE)" + "\r\n"));
_imapNs.Write(commandBytes, 0, commandBytes.Length);
_imapNs.Flush();
return Response();
}
Where I am wrong correct me thanks..
Do not use char array:
byte[] commandBytes = System.Text.Encoding.ASCII.GetBytes("$ UID FETCH " + index + " (BODYSTRUCTURE)" + "\r\n");
TCP is stream based and not message based.
This means that nothing guarantees that the entire message is received with the same Read. A Read may receive a half message, a complete message or two messages. You need to handle that accordingly.
3 Use return Encoding.ASCII.GetString(data, 0, ret);
4 There are several open source IMAP libraries out there. Why not use one of those since you are new to socket programming?

Categories