/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include <sys/socket.h>
#include <fcntl.h>
#include <netdb.h>
#include <errno.h>

void mailsend(char *hostname,char *to,char * from,char *subj,char *body)
{
  int sd,status,tmp;
  char *buf,ownhost[100];
  struct sockaddr local,remote;
  struct hostent *hostinfo;
  /* create socket */
  sd=socket(AF_INET,SOCK_STREAM,0);
  if(sd<0) {
      printf("Error creating socket: %s\n",strerror(errno));
      goto fin;
  }
  /* bind socket */
  local.sa_family=AF_INET;
  memset(local.sa_data,0,sizeof(local.sa_data));
  status=bind(sd,&local,sizeof(local));
  if(status<0) {
      printf("Error binding socket: %s\n",strerror(errno));
      goto fin;
  }
  /* lookup host */
  hostinfo=gethostbyname(hostname);
  if(!hostinfo) {
      printf("Error looking up host: %s\n",hostname);
      goto fin;
  }
  /* connect to host */
  remote.sa_family=hostinfo->h_addrtype;
  memcpy(remote.sa_data+2,hostinfo->h_addr_list[0],hostinfo->h_length);
  *((short *)remote.sa_data)=25;
  tmp=remote.sa_data[0];
  remote.sa_data[0]=remote.sa_data[1];
  remote.sa_data[1]=tmp;
  status=connect(sd,&remote,sizeof(remote));
  if(status!=0) {
      printf("Error connecting to host: %s port: %d\n",hostname,25);
      goto fin;
  }
  /* send email */
  gethostname(ownhost,sizeof(ownhost));
  buf = malloc(2000+strlen(body));
  sprintf(buf,"HELO %s\r\n"
              "MAIL FROM: <%s>\r\n"
              "RCPT TO: <%s>\r\n"
              "DATA\r\n"
              "Return-Path: <%s>\r\n"
              "From: %s\r\n"
              "To: %s\r\n"
              "Subject: %s\r\n"
              "MIME-version: 1.0\r\n"
              "Content-type: text/html; Charset=iso-8859-1\r\n"
              "\r\n"
              "%s\r\n"
              ".\r\n"
              "QUIT\r\n",ownhost,from,to,from,from,to,subj,body);
  status=send(sd,buf,strlen(buf),0);
  if(status<0) {
      printf("Error sending GET request\n");
      goto fin;
  }
  free(buf);
fin:
  close(sd);
  return;
}

int main(int argc,char *argv[])
{
  mailsend("minmailserver", "dig@ditdomain.dk", "mig@mitdomain.dk", "Dette er en test", "<a href='http://www.eksperten.dk/'>E</a>");
  return 0;
}
