Friday, March 25, 2011

GNU/C++ Simple Send Mail

See the Microsoft Visual C++ Simple Send Mail here.

I did the class below for GNU C++ based in these links:

SendMail.h:

#ifndef _SENDMAILHEADER
#define _SENDMAILHEADER

#include <sys/socket.h>
#include <arpa/inet.h>
#include <string>
#include <string.h>

#define HELO "HELO\r\n"
#define DATA "DATA\r\n"
#define QUIT "QUIT\r\n"

namespace mail {
class SendMail {
private:
int sock;
char buf[BUFSIZ];
void send_socket(char *s)
{
send(sock, s, strlen(s), 0);
//fprintf(stderr, s);
}
void read_socket()
{
int len = recv(sock, buf, BUFSIZ, 0);
//fprintf(stderr, ((std::string)buf).substr(0, len).c_str());
}
public:
char* HostIp;
unsigned short HostPort;
char* To;
char* From;
char* Subject;
char* Message;
SendMail() {
HostPort = 25;
};
~SendMail() { };
void Send() {
struct sockaddr_in hostAddr;
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
fprintf(stderr, "SendMail: socket() failed");
return;
}
hostAddr.sin_family = AF_INET;
hostAddr.sin_addr.s_addr = inet_addr(HostIp);
hostAddr.sin_port = htons(HostPort);
if (connect(sock, (struct sockaddr *) &hostAddr, sizeof(struct sockaddr_in)) != 0) {
fprintf(stderr, "SendMail: connect() failed");
return;
}
read_socket();
send_socket((char*)HELO);
read_socket();
send_socket((char*)"MAIL FROM: ");
send_socket(From);
send_socket((char*)"\r\n");
read_socket();
send_socket((char*)"VRFY ");
send_socket(From);
send_socket((char*)"\r\n");
read_socket();
send_socket((char*)"RCPT TO: ");
send_socket(To);
send_socket((char*)"\r\n");
read_socket();
send_socket((char*)DATA);
send_socket((char*)"Subject: ");
send_socket(Subject);
send_socket((char*)"\r\n");
read_socket();
send_socket(Message);
send_socket((char*)"\r\n");
send_socket((char*)".\r\n");
read_socket();
send_socket((char*)QUIT);
read_socket();
close(sock);
};
};
}

#endif


Usage:

#include "SendMail.h"

int main(int argc, char** argv) {
mail::SendMail* sendmail = new mail::SendMail();
sendmail->HostIp = (char*)"192.168.1.10";
sendmail->From = (char*)"mail@address.com";
sendmail->To = (char*)"mail@address.com";
sendmail->Subject = (char*)"Test!";
sendmail->Message = (char*)"Content:\nTest 123...";
sendmail->Send();
return 0;
}

No comments:

Post a Comment

Post a Comment