Mohammad Salman
Mohammad Salman

Reputation: 339

Send email with attachment in C++

I am working on a project in C++, which includes a feature of sending information to someone as 'email attachment'.

Everything is done except this 'email' thing. I do not know how to make this program able to send an email without using any email client or opening a browser. I have searched a lot over the internet but could not find any working thing (I do not have any knowledge of socket, Winsock, etc).

Upvotes: 27

Views: 106517

Answers (6)

shiponcs
shiponcs

Reputation: 1687

[libcurl][1] is free, good and easy one to start with. Along with dozens of other services, it supports SMTP and SMTPS.

It has lots example showing how to send an email using libcurl, see here

Upvotes: 0

Minhas Kamal
Minhas Kamal

Reputation: 22156

A Working Solution for Sending Email Using cURL


Download cURL from here, and extract. Now, run the executable from C++ code using WinExec() from windows.h.

Here is a demonstration for Gmail:

#include <windows.h>

int main(void){
    char* command = "curl smtp://smtp.gmail.com:587 -v --mail-from \"[email protected]\" --mail-rcpt \"[email protected]\" --ssl -u [email protected]:PASSWORD -T \"ATTACHMENT.FILE\" -k --anyauth";
    WinExec(command, SW_HIDE);
    return 0;
}

Place curl.exe in the same directory. Enter your email address and password in the command. Here, message is saved in a text file (ATTACHMENT.FILE).

Caution: The command may not support some special characters (like- &).


The above is just a demonstration of cURL. For practical usage you should go for libcurl. Here is a head-start for sending mail (works both with Windows and Linux).

Upvotes: 9

datenwolf
datenwolf

Reputation: 162184

Kudos to you for trying to code it yourself. This lifts you above the average script kiddy.

But shame yourself on spying on your brother. His private business is HIS business and none of yours.

Also, if your brother is only a bit clever, he'll not fall for some executable email attachment. Additionally, most email programs and webmailers will warn against executing this thing. If you were to make this foolproof you'd need to find vulnerabilities in the email client(s) used, to inject code, best way to go is attacking image loader and compression routines, but you'll have to find a 0day ideally, otherwise those exploits may have been patched before you get your spyware out. Some topics you may want to read upon are

  • stack overflow exploits
  • heap spraying
  • return based programming (used to counter W^X protection and mild implementations of address space randomization)

Sending email boils down to implement the SMTP protocol documented in http://www.faqs.org/rfcs/rfc821.html

Technically one could send an email directly to a target server, but those will usually reject mails coming directly from dialup connections, since this is a cheap yet effective method to counter spam. So you better go over an MTA with proper MX records. Freemailers are your friend, Hotmail is very popular for this. However you'll have to implement SMTP-Auth then, too. Documented in http://www.faqs.org/rfcs/rfc2554.html

Of course instead of sending an email you could as well just upload a file somewhere. Or you could implement IMAP and use a IMAP capable freemailer to store the data in the IMAP Drafts directory.

So if you manage to pull this off yourself, with your own code, then I think you deserve the success, but only if this doesn't involve third party libraries of malware construction kits (yes they exist).

Upvotes: 21

Shaun07776
Shaun07776

Reputation: 1052

indy also has components for sending emails via SMTP

TIdSMTP *IdSMTP1 = new TIdSMTP(this);
IdSMTP1->Host = "myhost";
IdSMTP1->Port = 25;
TIdMessage *MSG = new TIdMessage(this);
MSG->Clear();
MSG->From->Address = "[email protected]";
MSG->From->Name = "Someone";
MSG->Subject = "Spy Email";
MSG->Recipients->EMailAddresses = "[email protected]";
MSG->Body->Text = "your being watched ";
IdSMTP1->Connect();
IdSMTP1->Send(MSG);
IdSMTP1->Disconnect(true);
delete MSG;
delete IdSMTP1;

and it comes installed with Builder now

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 477140

I should recommend the fine VMime library. It's a true C++ library and handles everything email.

I'm also told that cURL has SMTP support.

Upvotes: 4

Davide Piras
Davide Piras

Reputation: 44605

I am not sure I agree with what you are doing in spying the users on what they do, but regardless here is some C++ code useful to send emails:

#define WIN32_LEAN_AND_MEAN

#include <stdio.h>
#include <stdlib.h>
#include <fstream.h>
#include <iostream.h>
#include <windows.h>
#include <winsock2.h>

#pragma comment(lib, "ws2_32.lib")

// Insist on at least Winsock v1.1
const VERSION_MAJOR = 1;
const VERSION_MINOR = 1;

#define CRLF "\r\n"                 // carriage-return/line feed pair

void ShowUsage(void)
{
  cout << "Usage: SENDMAIL mailserv to_addr from_addr messagefile" << endl
       << "Example: SENDMAIL smtp.myisp.com [email protected] [email protected] message.txt" << endl;

  exit(1);
}

// Basic error checking for send() and recv() functions
void Check(int iStatus, char *szFunction)
{
  if((iStatus != SOCKET_ERROR) && (iStatus))
    return;

  cerr << "Error during call to " << szFunction << ": " << iStatus << " - " << GetLastError() << endl;
}

int main(int argc, char *argv[])
{
  int         iProtocolPort        = 0;
  char        szSmtpServerName[64] = "";
  char        szToAddr[64]         = "";
  char        szFromAddr[64]       = "";
  char        szBuffer[4096]       = "";
  char        szLine[255]          = "";
  char        szMsgLine[255]       = "";
  SOCKET      hServer;
  WSADATA     WSData;
  LPHOSTENT   lpHostEntry;
  LPSERVENT   lpServEntry;
  SOCKADDR_IN SockAddr;

  // Check for four command-line args
  if(argc != 5)
    ShowUsage();

  // Load command-line args
  lstrcpy(szSmtpServerName, argv[1]);
  lstrcpy(szToAddr, argv[2]);
  lstrcpy(szFromAddr, argv[3]);

  // Create input stream for reading email message file
  ifstream MsgFile(argv[4]);

  // Attempt to intialize WinSock (1.1 or later)
  if(WSAStartup(MAKEWORD(VERSION_MAJOR, VERSION_MINOR), &WSData))
  {
    cout << "Cannot find Winsock v" << VERSION_MAJOR << "." << VERSION_MINOR << " or later!" << endl;

    return 1;
  }

  // Lookup email server's IP address.
  lpHostEntry = gethostbyname(szSmtpServerName);
  if(!lpHostEntry)
  {
    cout << "Cannot find SMTP mail server " << szSmtpServerName << endl;

    return 1;
  }

  // Create a TCP/IP socket, no specific protocol
  hServer = socket(PF_INET, SOCK_STREAM, 0);
  if(hServer == INVALID_SOCKET)
  {
    cout << "Cannot open mail server socket" << endl;

    return 1;
  }

  // Get the mail service port
  lpServEntry = getservbyname("mail", 0);

  // Use the SMTP default port if no other port is specified
  if(!lpServEntry)
    iProtocolPort = htons(IPPORT_SMTP);
  else
    iProtocolPort = lpServEntry->s_port;

  // Setup a Socket Address structure
  SockAddr.sin_family = AF_INET;
  SockAddr.sin_port   = iProtocolPort;
  SockAddr.sin_addr   = *((LPIN_ADDR)*lpHostEntry->h_addr_list);

  // Connect the Socket
  if(connect(hServer, (PSOCKADDR) &SockAddr, sizeof(SockAddr)))
  {
    cout << "Error connecting to Server socket" << endl;

    return 1;
  }

  // Receive initial response from SMTP server
  Check(recv(hServer, szBuffer, sizeof(szBuffer), 0), "recv() Reply");

  // Send HELO server.com
  sprintf(szMsgLine, "HELO %s%s", szSmtpServerName, CRLF);
  Check(send(hServer, szMsgLine, strlen(szMsgLine), 0), "send() HELO");
  Check(recv(hServer, szBuffer, sizeof(szBuffer), 0), "recv() HELO");

  // Send MAIL FROM: <[email protected]>
  sprintf(szMsgLine, "MAIL FROM:<%s>%s", szFromAddr, CRLF);
  Check(send(hServer, szMsgLine, strlen(szMsgLine), 0), "send() MAIL FROM");
  Check(recv(hServer, szBuffer, sizeof(szBuffer), 0), "recv() MAIL FROM");

  // Send RCPT TO: <[email protected]>
  sprintf(szMsgLine, "RCPT TO:<%s>%s", szToAddr, CRLF);
  Check(send(hServer, szMsgLine, strlen(szMsgLine), 0), "send() RCPT TO");
  Check(recv(hServer, szBuffer, sizeof(szBuffer), 0), "recv() RCPT TO");

  // Send DATA
  sprintf(szMsgLine, "DATA%s", CRLF);
  Check(send(hServer, szMsgLine, strlen(szMsgLine), 0), "send() DATA");
  Check(recv(hServer, szBuffer, sizeof(szBuffer), 0), "recv() DATA");

  // Send all lines of message body (using supplied text file)
  MsgFile.getline(szLine, sizeof(szLine));             // Get first line

  do         // for each line of message text...
  {
    sprintf(szMsgLine, "%s%s", szLine, CRLF);
    Check(send(hServer, szMsgLine, strlen(szMsgLine), 0), "send() message-line");
    MsgFile.getline(szLine, sizeof(szLine)); // get next line.
  } while(MsgFile.good());

  // Send blank line and a period
  sprintf(szMsgLine, "%s.%s", CRLF, CRLF);
  Check(send(hServer, szMsgLine, strlen(szMsgLine), 0), "send() end-message");
  Check(recv(hServer, szBuffer, sizeof(szBuffer), 0), "recv() end-message");

  // Send QUIT
  sprintf(szMsgLine, "QUIT%s", CRLF);
  Check(send(hServer, szMsgLine, strlen(szMsgLine), 0), "send() QUIT");
  Check(recv(hServer, szBuffer, sizeof(szBuffer), 0), "recv() QUIT");

  // Report message has been sent
  cout << "Sent " << argv[4] << " as email message to " << szToAddr << endl;

  // Close server socket and prepare to exit.
  closesocket(hServer);

  WSACleanup();

  return 0;
}

plenty of links on internet for a similar problem, I've found this:

http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/12345906-8a17-41c2-846f-fd3e1a135238/

Upvotes: 25

Related Questions