I'm trying to work with email data in my application. Everything works fine, I just need that when a new email arrives, it should also be read. This way only the emails are printed before the application starts. Is this possible in the EAGetEmails library using POP3 Server or do I have to program my own Sever or after some short time turn on and off the Application to update itself(This seems to me a rather clumsy solution)?
using EAGetMail;
using System;
using System.Globalization;
using System.IO;
namespace PopServer
{
class Program
{
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("popserver.com",
"username#mail.com",
"password",
ServerProtocol.Pop3);
oServer.SSLConnection = true;
oServer.Port = 995;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
//Here I tried to take advantage of the fact that if the application is connected via SSLConnection, it could update, but it only prints the emails before starting the application
while (oServer.SSLConnection)
{
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
Console.WriteLine("Body: {0}\r\n", oMail.TextBody);
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
oMail.SaveAs(fullPath, true);
//Delete email-isRead
//oClient.Delete(info);
}
}
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
EAGetMail is not really popular,you can take a look on this library : https://www.nuget.org/packages/OpenPop.NET/
public static List<Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
{
// The client disconnects from the server when being disposed
using(Pop3Client client = new Pop3Client())
{
// Connect to the server
client.Connect(hostname, port, useSsl);
// Authenticate ourselves towards the server
client.Authenticate(username, password);
// Get the number of messages in the inbox
int messageCount = client.GetMessageCount();
// We want to download all messages
List<Message> allMessages = new List<Message>(messageCount);
// Messages are numbered in the interval: [1, messageCount]
// Ergo: message numbers are 1-based.
// Most servers give the latest message the highest number
for (int i = messageCount; i > 0; i--)
{
allMessages.Add(client.GetMessage(i));
}
// Now return the fetched messages
return allMessages;
}
}
Then you just have to code a little loop to check email every few secondes.
Related
I'm trying to retrieve data from email and then work with it. Everything is fine, I can get the data, but I need to get the most recent ones. When I run this code and send an email in the process, it doesn't come up until I turn it on. I have tried turning the SSL connection or client to the server on and off and back on again (like some kind of update, but with the same result).
Thanks for any reaction or ideas. :)
using EAGetMail;
using System;
using System.Globalization;
using System.IO;
namespace PopServer
{
class Program
{
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("popserver.com",
"username#mail.com",
"password",
ServerProtocol.Pop3);
oServer.SSLConnection = true;
oServer.Port = 995;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
//Here I tried to take advantage of the fact that if the application is connected via SSLConnection, it could update, but it only prints the emails before starting the application
while (oServer.SSLConnection)
{
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
Console.WriteLine("Body: {0}\r\n", oMail.TextBody);
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
oMail.SaveAs(fullPath, true);
//Delete email-isRead
//oClient.Delete(info);
}
}
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
try
{
bool help = true;
do{
string localInbox = string.Format("{0}\\inbox",
Directory.GetCurrentDirectory());
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("popserver.com",
"username#mail.com",
"password",
ServerProtocol.Pop3);
oServer.SSLConnection = true;
oServer.Port = 995;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
//Here I tried to take advantage of the fact that if the application is connected via SSLConnection, it could update, but it only prints the emails before starting the application
while (oServer.SSLConnection)
{
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
Console.WriteLine("Body: {0}\r\n", oMail.TextBody);
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
oMail.SaveAs(fullPath, true);
//Delete email-isRead
//oClient.Delete(info);
}
}
Console.WriteLine("Again?");
Console.WriteLine("1-y");
Console.WriteLine("2-n");
int a = Convert.ToInt32(Console.ReadLine());
if (a == 2)
{
help = false;
}
//Just easily restarted hole code
while(help != false)
oClient.Quit();
Console.WriteLine("Completed!");
I want to automatically open or click a http link from the Outlook mail body.
I am using MailServer.
Here my code:
// Some function...
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}; Flags: {3}",
info.Index, info.Size, info.UIDL, info.Flags);
// Receive email from POP3 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("To: {0}", oMail.To.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
if (oMail.Attachments.Length > 0)
{
for (int j = 0; j <= oMail.Attachments.Length - 1; j++)
{
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("MMddyyyyHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailbox, sdate, d.Millisecond.ToString("d3"), i);
// Save email to local disk
oMail.SaveAs(fileName, true);
// Save attachments in specific folders.
oMail.Attachments[j].SaveAs(#"D:\"{Folder Name}"\" + oMail.Attachments[j].Name, true); // find the said path
// Mark email as deleted from POP3 server.
oClient.Delete(info);
}
}
// Generate an email file name based on date time.
}
// Quit and purge emails marked as deleted from POP3 server.
oClient.Quit();
}
Please give me any idea.
I am trying to read voltage measurements from my Unisource 4100 GPIB DMM. I know I can connect to the device because I get appropriate responses with the commands '*RST' and '*IDN?', however I cannot get any responses with other commands such as 'SYST:ERR?' or 'CONF:VOLT:DC 1000, 0.001'. I have tested out the code I am trying with on the Agilent 34410A and managed to get the responses I want, but not with the Unisource 4100. I am using the NI GPIB-USB-HS controller to interface with. I have included the code below. Should the SCPI commands not work for all GPIB interfaces? What changes would I have to make to elicit a response from the Unisource 4100?
I have included some code for reference:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using Ivi.Visa.Interop;
namespace CsharpExample
{
class VoltageExample
{
static void Main(string[] args)
{
VoltageExample DmmClass = new VoltageExample(); //Create an instance of this class so we can call functions from Main
Ivi.Visa.Interop.ResourceManager rm = new Ivi.Visa.Interop.ResourceManager(); //Open up a new resource manager
Ivi.Visa.Interop.FormattedIO488 myDmm = new Ivi.Visa.Interop.FormattedIO488(); //Open a new Formatted IO 488 session
try
{
string DutAddr = "GPIB0::12::INSTR"; //String for GPIB
myDmm.IO = (IMessage)rm.Open(DutAddr, AccessMode.NO_LOCK, 10000, ""); //Open up a handle to the DMM with a 2 second timeout
//myDmm.IO.Timeout = 20000;
myDmm.IO.Clear(); //Send a device clear first
myDmm.WriteString("*RST", true); //Reset the device
myDmm.WriteString("*IDN?", true); //Get the IDN string
string IDN = myDmm.ReadString();
Console.WriteLine(IDN); //report the DMM's identity
myDmm.WriteString("*TST?", true); //Get the IDN string
Thread.Sleep(5000);
string TST = myDmm.ReadString();
Console.WriteLine(TST); //report the DMM's identity
myDmm.WriteString("SYST:ERR?", true); //Get the IDN string
string ERR = myDmm.ReadString();
Console.WriteLine(ERR); //report the DMM's identity
myDmm.WriteString("CONF:VOLT:DC 1000, 0.001", true);
DateTime time = DateTime.Now; //Timer to measure the time difference to get all the readings
TimeSpan diff;
Console.WriteLine("Measurement in Volts");
for(int i = 0; i<10; i++){
//Configure for DCV 100V range, 100uV resolution
myDmm.WriteString("READ?", true);
String DCVResult = myDmm.ReadString();
Console.WriteLine("DCV Reading = " + DCVResult); //report the DCV reading
DmmClass.CheckDMMError(myDmm); //Check if the DMM has any errors
Thread.Sleep(1000);
diff = DateTime.Now.Subtract(time);
//diff = DateTime.Now.Subtract(time.AddSeconds(1).AddMilliseconds(20));
Console.WriteLine("\t\t\t" + diff);
}
myDmm.WriteString("CONF:RES 100, MAX", true);
Console.WriteLine("Measurement in Ohms");
for (int i = 0; i < 10; i++)
{
//Configure for res 1000 Ohm range, 100uV resolution
myDmm.WriteString("READ?", true);
String OHMResult = myDmm.ReadString();
Console.WriteLine("Resistance Measurement = " + OHMResult); //report the DCV reading
DmmClass.CheckDMMError(myDmm); //Check if the DMM has any errors
Thread.Sleep(500);
}
}
catch (Exception e)
{
Console.WriteLine("Error occured: " + e.Message);
}
finally
{
//Close out your resources
try { myDmm.IO.Close(); }
catch{}
try{ System.Runtime.InteropServices.Marshal.ReleaseComObject(myDmm);}
catch {}
try{
System.Runtime.InteropServices.Marshal.ReleaseComObject(rm);
}
catch {}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
I am developing a Console application which will monitor Exchange server and download attachments(XML Files) from new emails. I have used EaGetmail for this.
Attachments are downloading to target folder but it is empty. Looking for a solution.
This is my sample code, Any suggestions Pls.
private static void CheckInboxforEmail()
{
// Use domain\user as the user name
MailServer oServer = new MailServer("MailID", "domain","Pwd",ServerProtocol.ExchangeEWS);
MailClient oClient = new MailClient("TryIt");
oServer.SSLConnection = true;
try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
// Receive email from Exchange server
Mail oMail = oClient.GetMail(info);
//SaveAttachments
foreach (EAGetMail.Attachment Att in oMail.Attachments)
{
string AttName = String.Format("{0}\\{1}", WIPFolder,Att.Name);
oMail.SaveAs(AttName, true);
}
// Delete email from EWS server.
oClient.Delete(info);
}
// Quit from Exchange server.
oClient.Quit();
}
catch (Exception ep)
{
}
}
Try this it worked for me!!!!
//Get Attachments
Attachment[] atts = oMail.Attachments;
int count = atts.Length;
//Store Attachments
for (int ai = 0; ai < count; ai++)
{
Attachment att = atts[ai];
string attname = String.Format("{0}\\{1}", mailbox, att.Name);
att.SaveAs(attname, true);
}
I'm trying to write a voting server and client, so you start the program and it displays the voting form and you can vote on various items. For the server part I've got the server running in a separate thread, but it's using a lot of CPU, how do I reduce the amount of CPU it's using?
this is my server:
Form1 main = new Form1();
try
{
IPAddress ipAd = IPAddress.Parse(main.ipAddress); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 55548);
/* Start Listeneting at the specified port */
myList.Start();
while (true)
{
string message = "";
Socket s = myList.AcceptSocket();
if (main.users.Contains(s.RemoteEndPoint.ToString()) == false)
main.users.Add(s.RemoteEndPoint.ToString());
byte[] b = new byte[500];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
{
message += (Convert.ToString(b[i]));
}
string[] messageArray = message.Split('/');
MessageBox.Show("help");
if (messageArray[0].CompareTo("vote") == 0)
{
if (main.votes.ContainsKey(messageArray[1]) != true) main.votes.Add(messageArray[1], 1);
else main.votes[messageArray[1]]++;
string[] temp = main.textBox1.Text.Split(' ');
int numVotes = Convert.ToInt32(temp[1]);
numVotes++;
main.textBox1.Text = temp[0] + " " + Convert.ToString(numVotes);
}
if (messageArray[0].CompareTo("start") == 0)
{
main.updateEverything();
}
if(messageArray[0].CompareTo("withdraw") == 0)
{
main.votes[messageArray[1]]--;
string[] temp = main.textBox1.Text.Split(' ');
int numVotes = Convert.ToInt32(temp[1]);
numVotes--;
main.textBox1.Text = temp[0] + " " + Convert.ToString(numVotes);
}
/* clean up */
s.Close();
myList.Stop();
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
You are using a blocking type of connection. The loop you create causes a CPU overhead because of the TcpListener.AcceptConnection(). Your solution is to accept non-blocking socket connections, which is done by receiving data from socket asynchronously.
Here's the msdn link that explains how it works.
http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx
I see you have string concatenations which basically affects performance; try using a StringBuilder - the message variable should be of type StringBuilder.