[ACCEPTED]-sending an email from a C/C++ program in linux-gmail

Accepted answer
Score: 26

You could invoke your local MTA directly 1 using popen() and feed it RFC822-compliant text.

#include <stdio.h>
#include <string.h>
#include <errno.h>
int sendmail(const char *to, const char *from, const char *subject, const char *message)
    int retval = -1;
    FILE *mailpipe = popen("/usr/lib/sendmail -t", "w");
    if (mailpipe != NULL) {
        fprintf(mailpipe, "To: %s\n", to);
        fprintf(mailpipe, "From: %s\n", from);
        fprintf(mailpipe, "Subject: %s\n\n", subject);
        fwrite(message, 1, strlen(message), mailpipe);
        fwrite(".\n", 1, 2, mailpipe);
        retval = 0;
     else {
         perror("Failed to invoke sendmail");
     return retval;

main(int argc, char** argv)
    int i;

    printf("argc = %d\n", argc);

    for (i = 0; i < argc; i++)
        printf("argv[%d] = \"%s\"\n", i, argv[i]);
    sendmail(argv[1], argv[2], argv[3], argv[4]);
Score: 5

libESMTP seems to be what you are looking for. It's 5 very well documented and also seems to be 4 under active development (last Release Candidate 3 is from mid-January 2012). It also supports 2 SSL and various authentication protocols.

There 1 are example applications in the source package.

Score: 2

Both VMime and libcurl are good libraries for email 1 sending (and more).

Score: 1

I like the answer of trojanfoe above, BUT 15 in my case I needed to turn on an email 14 sending agent.. an MTA to enable linux to 13 send emails - I have found exim4 to be 12 a relatively simple MTA to get working and 11 that trojanfoe's program works very nicely 10 with it.

to get it to work I used (on a debian 9 type system in a virtual box (crunchbang 8 linux))

sudo apt-get install exim

sudo apt-get 7 install mailutils

I configured exim4 with

sudo 6 dpkg-reconfigure exim4-config

and I told 5 the computer about my normal (remote) email 4 address with

sudo emacs /etc/email-addresses

hope 3 this might be useful as these were the steps 2 I found worked to get my linux system sending 1 email with trojanfoe's email program above

Score: 1

Do a fork exec and pipe the body to a program 1 like sendmail/mail:

#include <string>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

using std::string;

static const int READEND = 0;
static const int WRITEEND = 1;

int sendEmail(const string& to, const string& subject, const string& body) {
  int p2cFd[2];

  int ret = pipe(p2cFd);
  if (ret) {
    return ret;

  pid_t child_pid = fork();
  if (child_pid < 0) {

    return child_pid;
  else if (!child_pid) {
    dup2(p2cFd[READEND], READEND);

    execlp("mail", "mail", "-s", subject.c_str(), to.c_str(), NULL);



  ret = write(p2cFd[WRITEEND], body.c_str(), body.size());
  if (ret < 0) {
    return ret;


  if (waitpid(child_pid, &ret, 0) == -1) {
    return ret;

  return 0;

int main() {
  return sendEmail("email@hostname.com", "Subject", "Body");

More Related questions