#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #define HELO "HELO\n" #define DATA "DATA\n" #define QUIT "QUIT\n" FILE *fin; int sock; struct sockaddr_in server; struct hostent *hp, *gethostbyname(); char buf[BUFSIZ+1]; int len; char *host_id; char *from_id; char *to_id; char *file_id; char wkstr[100]; /*=====Send a string to the socket=====*/ send_socket(char *s) { write(sock,s,strlen(s)); write(1,s,strlen(s)); } /*=====Read a string from the socket=====*/ read_socket() { len = read(sock,buf,BUFSIZ); write(1,buf,len); } /*=====MAIN=====*/ int main(int argc, char* argv[]) { if(argc != 5) { printf("USAGE: %s <host> <from> <to> <filename>\n\n", argv[0]); exit(1); } host_id=argv[1]; from_id=argv[2]; to_id=argv[3]; file_id=argv[4]; /*=====Create Socket=====*/ sock = socket(AF_INET, SOCK_STREAM, 0); if (sock==-1) { perror("opening stream socket"); exit(1); } /*=====Verify host=====*/ server.sin_family = AF_INET; hp = gethostbyname(host_id); if (hp==(struct hostent *) 0) { fprintf(stderr, "%s: unknown host\n", host_id); exit(2); } /*=====Connect to port 25 on remote host=====*/ printf ("hostent %s\n", hp->h_addr_list[0]); memcpy((char *) &server.sin_addr, (char *) hp->h_addr, hp->h_length); server.sin_port=htons(25); /* SMTP PORT */ if (connect(sock, (struct sockaddr *) &server, sizeof server)==-1) { perror("connecting stream socket"); exit(1); } /*=====Write some data then read some =====*/ read_socket(); /* SMTP Server logon string */ send_socket(HELO); /* introduce ourselves */ read_socket(); /*Read reply */ send_socket("MAIL from: "); /* Mail from us */ send_socket(from_id); send_socket("\n"); read_socket(); /* Sender OK */ send_socket("RCPT To: "); /*Mail to*/ send_socket(to_id); send_socket("\n"); read_socket(); /*Recipient OK*/ send_socket(DATA);/*body to follow*/ read_socket(); /*ok to send */ fin=fopen(file_id, "r"); /* open file */ while(1) { if(fgets(wkstr, 100, fin)==NULL) break; /* exit on EOF */ send_socket(wkstr); } fclose(fin); /* close file */ send_socket(fin); /*send file*/ send_socket(".\n"); read_socket(); /* OK*/ send_socket(QUIT); /* quit */ read_socket(); /* log off */ /*=====Close socket and finish=====*/ close(sock); exit(0); }
You need to create an account or log in to post comments to this site.