This snippet shows how to connect to a pop3 mail server.
Program.cs
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main(string[] args)
{
POP3 popClient = new POP3("");
popClient.Username = "";
popClient.Password = "";
popClient.Authenticate();
Console.WriteLine("Total Messages in INBOX: " + popClient.MessageCount);
int MessageCount = popClient.MessageCount;
ArrayList message = new ArrayList();
for (int i = 1; i < MessageCount; i++)
{
message = popClient.GetHeaders(1);
Console.WriteLine(message[0]);
Console.WriteLine(message[1]);
}
Console.ReadKey();
}
}
POP3.cs
class POP3
{
private TcpClient tcpClient;
private StreamReader sReader;
private StreamWriter sWriter;
private NetworkStream nStream;
private string username = "";
private string password = "";
public POP3(string host)
{
try
{
tcpClient = new TcpClient(host, 110);
if (tcpClient.Connected)
{
nStream = tcpClient.GetStream();
sReader = new StreamReader(nStream);
sWriter = new StreamWriter(nStream);
Console.WriteLine("Connected To POP Server");
Console.WriteLine("Host: " + host);
Console.WriteLine(GetResponse());
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private string GetResponse()
{
string response ="";
while (true)
{
response += sReader.ReadLine();
if (response !=".")
{
break;
}
}
return response;
}
public string Username
{
set
{
this.username = value;
}
}
public string Password
{
set
{
this.password = value;
}
}
public void Authenticate()
{
sWriter.WriteLine("User " + this.username);
sWriter.Flush();
Console.WriteLine(GetResponse());
sWriter.WriteLine("Pass " + this.password);
sWriter.Flush();
Console.WriteLine(GetResponse());
}
public int MessageCount
{
get
{
sWriter.WriteLine("stat");
sWriter.Flush();
string[] splitResponse = GetResponse().Split(' ');
return Convert.ToInt32(splitResponse[1]);
}
}
public ArrayList GetHeaders(int index)
{
ArrayList message = new ArrayList();
sWriter.WriteLine("top " + index + " 0");
sWriter.Flush();
string response;
while (true)
{
response = sReader.ReadLine();
if (response ==".")
{
break;
}
if (response.Length > 4)
{
try
{
if (response.Substring(0, 5) == "From:")
{
message.Add(response);
}
if (response.Substring(0, 8) == "Subject:")
{
message.Add(response);
}
}
catch { }
}
}
return message;
}
}
No comments:
Post a Comment