/*
 * mail.c
 * by xeon
 *
 * Send a file as email text.
*/

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>

int main (int argc, char **argv)
{
	int fd, cont=10;
	struct sockaddr_in sa;
	struct hostent *server;
	char sFrom[100], sTo[100], sF[11], sBuff[256];
	FILE *f;

	if (argc != 3) {
		printf ("Usage : %s <smtp server> <file>\n", argv[0]);
		return 0;
	}

	if (-1 == (fd = socket (AF_INET, SOCK_STREAM, 0))) return -1;

	if (NULL == (server = gethostbyname (argv[1]))) return -1;

	if (NULL == (f = fopen (argv[2], "r"))) {
		printf ("Can't open file %s\n", argv[2]);
		return -1;
	}

	sa.sin_addr = *(struct in_addr *) server->h_addr;
 	sa.sin_port = htons (25);
      	sa.sin_family = AF_INET;
      	bzero (&(sa.sin_zero), 8);

	if (-1 == connect (fd, (struct sockaddr *)&sa, sizeof(struct sockaddr))) {
		printf ("Can't connect to server %s\n", argv[1]);
		return -1;
	}

	cont = read (fd, sBuff, 256);
	printf ("%s", sBuff); bzero (sBuff, cont);

	printf ("helo anonymous@anon.org\n");
	send (fd, "helo anonymous@anon.org\n", strlen("helo anonymous@anon.org\n"), 0);
	cont = read (fd, sBuff, 256);
	printf ("%s", sBuff); bzero (sBuff, cont);

	printf ("mail from: "); scanf ("%s", sFrom);
	send (fd, "mail from: ", 11, 0); send (fd, sFrom, strlen (sFrom), 0); send (fd, "\n", 1, 0);
	cont = read (fd, sBuff, 256);
	printf ("%s", sBuff); bzero (sBuff, cont);

	printf ("rcpt to: "); scanf ("%s", sTo);
	send (fd, "rcpt to: ", 9, 0); send (fd, sTo, strlen (sTo), 0); send (fd, "\n", 1, 0);
	cont = read (fd, sBuff, 256);
	printf ("%s", sBuff); bzero (sBuff, cont);

	printf ("data\n");
	send (fd, "data\n", 5, 0);
	cont = read (fd, sBuff, 256);
	printf ("%s", sBuff); bzero (sBuff, cont);

	do {
		cont = fread (sF, 1, 10, f);
		send (fd, sF, cont, 0);
	} while ((cont==10) && (!feof(f)));

	printf ("\r\n\r\n.\r\n");
	send (fd, "\r\n\r\n.\r\n", 7, 0);
	cont = read (fd, sBuff, 256);
	printf ("%s", sBuff); bzero (sBuff, cont);

	printf ("quit\n");
	send (fd, "quit\n", 5, 0);
	cont = read (fd, sBuff, 256);
	printf ("%s", sBuff); bzero (sBuff, cont);

	fclose (f);
	close (fd);

	return 0;
}
