用C写邮件收发程序

刚刚抄来的,呵呵

#include
#include
#include
#include
#pragma comment (lib,"ws2_32.lib")
//Global variable
char server[40],to[40],from[40],subject[40],data[1024],szSend[7][2048];
int times;
struct sockaddr_in sa;
void usage(char *name)
{
printf("\n%s by eyas"
  "\n2001/2/28"
  "\nUsage:%s "
  "\nExample:%s 202.104.32.230 [email protected] [email protected] hello haha 100\n",
  name,name,name);
return;
}
DWORD WINAPI SendMail(PVOID p)
{
WSADATA wsd;
int net,ret,i,j;
char szBuffer[2048];
if(WSAStartup(MAKEWORD(1,1),&wsd)!=0)
{
 printf("\nFailed to load Winsock library!ErrorCode:%d.",GetLastError());
 ExitProcess(1);
}
net=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(net==INVALID_SOCKET)
{
 printf("\nsocket() failed.ErrorCode:%d.",GetLastError());
 WSACleanup();
 ExitProcess(1);
}
ret=connect(net, (struct sockaddr *) &sa, sizeof sa);
if(ret!=0)
{
 printf("\nconnect() failed.ErrorCode:%d.",GetLastError());
 closesocket(net);
 WSACleanup();
 ExitProcess(1);
}

for(j=0;j<8;j++)
{
 //receive data
 ret=recv(net,szBuffer,2048,0);
 if((ret==0) || (ret==SOCKET_ERROR))
 {
  printf("\nrecv() failed.ErrorCode:%d.",WSAGetLastError());
  break;
 }
 
 if(j==7)
  break;
 echo send data
 printf("%s",szSend[j]);
 send data
 ret=send(net,szSend[j],strlen(szSend[j]),0);
 if((ret==0) || (ret==SOCKET_ERROR))
 {
  printf("\nsend() failed.ErrorCode:%d.",WSAGetLastError());
  break;
 }
}
//free resource
closesocket(net);
WSACleanup();
return 0;
}
int main(int argc,char **argv)
{
HANDLE hThread;
DWORD dwThreadId;
int i;
if(argc!=7)
{
 usage(argv[0]);
 return 1;
}
//gets user input
strncpy(server,argv[1],sizeof(server));
strncpy(to,argv[2],sizeof(to));
strncpy(from,argv[3],sizeof(from));
strncpy(subject,argv[4],sizeof(subject));
strncpy(data,argv[5],sizeof(data));
times=atoi(argv[6]);
strncpy((char *)&sa, "", sizeof sa);
//fill the struct
sa.sin_family=AF_INET;
sa.sin_port=htons(25);
sa.sin_addr.s_addr=inet_addr(server);
///built send data
strcpy(szSend[0],"HELO\n");
strcpy(szSend[1],"MAIL FROM:<");
strncat(szSend[1],from,sizeof(from));
strcat(szSend[1],">\n");
strcpy(szSend[2],"RCPT TO:<");
strncat(szSend[2],to,sizeof(to));
strcat(szSend[2],">\n");
strcpy(szSend[3],"DATA\n");
strcpy(szSend[4],"Subject:");
strncat(szSend[4],subject,sizeof(subject));
strcat(szSend[4],"\nFrom:");
strncat(szSend[4],from,sizeof(from));
strcat(szSend[4],"\n\n");
strncat(szSend[4],data,sizeof(data));
strcat(szSend[4],"\n.\n");
strcpy(szSend[5],"SEND\n");
strcpy(szSend[6],"QUIT\n");
for(i=0;i {
 hThread=CreateThread(NULL,0,SendMail,(PVOID)NULL,0,&dwThreadId);
 if(hThread==NULL)
 {
  printf("\nCreate thread error.");
  break;
 }
 Sleep(20);
 CloseHandle(hThread);
 printf("\nHave been send %d Email.",i+1);
}
printf("\nWait 5 seconds to exit.");
Sleep(5000);
printf("\nComplete.");
return 0;
}

你可能感兴趣的:(C/C)