1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
static void sendmail_write(const int sock,const char *str,const char *arg)
{
char buf[4096];
if (arg != NULL)
snprintf(buf, sizeof(buf), str, arg);
else
snprintf(buf, sizeof(buf), str);
send(sock, buf, strlen(buf), 0);
// read a reply from server
char outbuf[1024];
int len=recv(sock,outbuf,1024,0);
outbuf[len]='\0';
cout <<outbuf;
}
static int sendmail(
const char *from,
const char *to,
const char *subject,
const char *body,
const char *hostname,
const int port
) {
struct hostent *host;
struct sockaddr_in saddr_in;
int sock = 0;
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
return -1;
}
sock = socket(AF_INET, SOCK_STREAM, 0);
host = gethostbyname(hostname);
saddr_in.sin_family = AF_INET;
saddr_in.sin_port = htons((u_short)port);
saddr_in.sin_addr.s_addr = 0;
memcpy((char*)&(saddr_in.sin_addr), host->h_addr, host->h_length);
if (connect(sock, (struct sockaddr*)&saddr_in, sizeof(saddr_in)) == -1) {
return -2;
}
sendmail_write(sock, "EHLO %s\n", "Testname"); // Should I use HELO or EHLO?
sendmail_write(sock, "STARTTLS\n",""); // <----- starting TLS?
sendmail_write(sock, "MAIL FROM: %s\n", from); // from
sendmail_write(sock, "RCPT TO: %s\n", to); // to
sendmail_write(sock, "DATA\n", NULL); // begin data
sendmail_write(sock, "From: %s\n", from);
sendmail_write(sock, "To: %s\n", to);
sendmail_write(sock, "Subject: %s\n", subject);
sendmail_write(sock, "\n", NULL);
sendmail_write(sock, "%s\n", body); // data
sendmail_write(sock, ".\n", NULL); // end data
sendmail_write(sock, "QUIT\n", NULL); // terminate
closesocket(sock);
return 0;
}
int main(int argc, char *argv[]) {
int ret = sendmail(
"mack_whipp@hotmail.com", // from - put an email address here
"mack_whipp@hotmail.com", // to - put an email address here
"subject_sendmail",
"body_text",
"smtp.gmail.com",
25
);
if (ret != 0)
{
fprintf(stderr, "Failed to send mail (code: %i).\n", ret);
system("pause");
}
else
{
fprintf(stdout, "Mail successfully sent.\n");
system("pause");
}
return ret;
}
|