Introduction
Did you ever have the need to parse your emails and extract / use the received data some other way? Perhaps, store numbers to a database? Or start/control something via, let's say, your mobile phone? If so, then this is the article for you. Of course, there is a whole automation business out there. But the advantage of this article is that it is free, simple, small, and effective (C++).
The Code
#include <windows.h>
#include <winsock.h>
#include <stdio.h>
#define POPCMD(cmd,prm) sprintf(buf,cmd,prm);\
if(send(s,buf,strlen(buf),0) <= 0 && *buf > 0 ) return 0;\
if(recv(s,buf,size ,0) <= 0 || *buf != '+' ) return 0;
char* ReadMail(char* host, char* user, char* pass, int no, int& count, int& size) {
HOSTENT* dns=gethostbyname(host); if(!dns) return 0;
char* &ip=dns->h_addr, data[64], *buf=data; size=64;
sockaddr_in a={AF_INET,htons(110), ip[0],ip[1],ip[2],ip[3]};
SOCKET s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(connect(s,(sockaddr*)&a,sizeof(a)) <0 ) return 0;
POPCMD("" ,no);
POPCMD("user %s\n" ,user);
POPCMD("pass %s\n" ,pass);
POPCMD("stat\n" ,no); count = atol(buf+4);
POPCMD("retr %d\n" ,no); size = atol(buf+4);
int i=0; char *ptr=buf=new char[size+1]; ptr[size]=0;
do buf+=i=recv(s,buf,size,0); while(i>0 && buf-ptr<size);
closesocket(s);
return ptr;
}
int WINAPI WinMain(HINSTANCE inst,HINSTANCE prev,LPSTR cmd,int show){
WSADATA wsa; WSAStartup(MAKEWORD(1,1),&wsa); char* data;
while(1) {
for(int no=1,count=1,size=0;no<=count;no++) {
if( data = ReadMail("pop.punkass.com", "shaved", "asdf1", no, count, size) ) {
if(strstr(data, "show this")) MessageBox(0,data,0,0);
if(strstr(data, "start notepad")) WinExec("notepad",SW_SHOW);
delete data;
}
}
Sleep(1*60*1000);
}
}
Points of Interest
This sample checks all the emails on the email server (via the POP3 protocol) for specific strings. If they are found, a specific action is performed. In this case, the mail is shown via a message box or Notepad is started.
To build the sample, just create a new Win32 C++ project in your dev environment and paste it there. It uses Winsock, so add wsock32.lib to the linker input. Keep in mind that it only works with email servers supporting unencrypted POP3 protocol. You may easily check your server by running "telnet youremailserver 110". You should get a reply like, "+OK Hello there." And, if not, then don't worry, there is a plethora of free POP email account providers on the Internet.
Place for Improvements
In this sample, actions are repeated every minute since mails are not deleted. To delete mails, just add this line below the retr command, like this:
POPCMD("retr %d\n" ,no); size = atol(buf+4);
POPCMD("dele %d\n" ,no);
Also, the sample can receive large binary files. These are usually in some form of binary to text encoding due to fact that POP3 is a text based protocol; so prepare for this.
POP3 Protocol Details
Enjoy it, and don't forget to check other POP3 commands here.