Skip to content

Instantly share code, notes, and snippets.

@mayank
Created November 12, 2013 23:53
Show Gist options
  • Save mayank/7440949 to your computer and use it in GitHub Desktop.
Save mayank/7440949 to your computer and use it in GitHub Desktop.
SMTP File Transfer using C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h> /* gethostbyname */
#include <netinet/in.h> /* htons */
#include <sys/socket.h>
#include <sys/types.h>
int main()
{
const char* hostname = "google.com";
int port = 25;
// address to host
struct sockaddr_in server_address;
// host information
struct hostent *host;
// socket file descriptor
int sock = 0;
// step - 1
// create socket connection
sock = socket( AF_INET, SOCK_STREAM, 0 );
// ( type of service, type of socket, type of protocol )
// step - 2
// configure the address
server_address.sin_family = AF_INET;
server_address.sin_port = htons( (unsigned short) port );
server_address.sin_addr.s_addr = 0;
// step - 3
// getting host information
host = gethostbyname( hostname );
// step - 4
// copying host address to server field
memcpy( (char *) &server_address.sin_addr, host->h_addr, host->h_length );
// ( jahan copy karna hai, jo copy karna hai, copy karne ka size )
// step - 5
// connect to server
connect( sock, (struct sockaddr *) &server_address, sizeof( server_address ));
// ( file desc sock, address, sizeof address )
// step -6
// send the mail
/*
* HELO [email protected]
* MAIL FROM: [email protected]
* RCPT TO: [email protected]
* DATA
* From: [email protected]
* To: [email protected]
* Subject: Le mera mail
*
* Madarchod mail padh le
* .
* QUIT
*
*/
const char* from = "[email protected]";
const char* to = "[email protected]";
const char* subject = "Le mera Mail";
const char* body = "madarchod mail padh mera";
sendmail( sock, "HELO %s\n", from );
sendmail( sock, "MAIL FROM: %s\n", from );
sendmail( sock, "RCPT TO: %s\n", to );
sendmail( sock, "DATA\n", NULL );
sendmail( sock, "From: %s\n", from );
sendmail( sock, "To: %s\n", to );
sendmail( sock, "Subject: %s\n\n", subject );
sendmail( sock, "%s\n.\nQUIT\n", body );
// step - 7
// closing connection
close( sock );
return 0;
}
void sendmail( int sock, char *str, const char *data )
{
// send -> ( file desc sock, string, string length , 0 )
// recv
char buffer[1024];
snprintf( buffer, 1024, str, data );
// ex : printf( str, data ) -> printf(" MAIL FROM: %s\n", from );
send( sock, buffer, strlen(buffer), 0 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment