tags:

views:

195

answers:

4

I'm just wondering how can I send email using C? I Googled it a little bit, but could not find anything proper.

+1  A: 

Run sendmail and pass the e-mail to its standard input (on unix-like systems), or use some SMTP client library to connect to SMTP mail server.

Messa
+2  A: 

The most obvious choices:

  1. Use system() to call an existing command-line tool to send mail. Not very portable (requires an external tool with a given calling syntax, etc) but very easy to implement.
  2. Use some library.
  3. Implement SMTP yourself, and talk directly to a mail server. A lot of work.
unwind
Indeed i want to learn how to implement SMTP myself as you mentioned in your third option. Do you know any related tutorial, article or source code?
mehmet6parmak
In future, try not to recommend system() and instead the exec() family of functions.
Mustapha Isyaku-Rabiu
@rogue: Thanks. But system() is more portable, exec*() is Unix only.
unwind
@mehmet6parmak. Start here -> http://tools.ietf.org/html/rfc2821
Alexander Pogrebnyak
@unwind: it's usually irrelevant, since the command you want to execute is already less portable than the function you use to execute it. E.g, there's not much point insisting on `system("/usr/sbin/sendmail whatever");`, because any system that doesn't have `exec*` isn't going to have `/usr/sbin/sendmail` either. If the command is user-configurable, though, you're in with a chance that system can be made to work.
Steve Jessop
I'm referring to the fact that we do not use system() from a program with set-user-ID or set-group-ID privileges, because strange values for some environment variables might be used to subvert system integrity.
Mustapha Isyaku-Rabiu
+3  A: 

On Unix like systems you can use system and sendmail as follows:

#include <stdio.h>
#include <string.h>

int main() {

        char cmd[100];  // to hold the command.
        char to[] = "[email protected]"; // email id of the recepient.
        char body[] = "SO rocks";    // email body.
        char tempFile[100];     // name of tempfile.

        strcpy(tempFile,tempnam("/tmp","sendmail")); // generate temp file name.

        FILE *fp = fopen(tempFile,"w"); // open it for writing.
        fprintf(fp,"%s\n",body);        // write body to it.
        fclose(fp);             // close it.

        sprintf(cmd,"sendmail %s < %s",to,tempFile); // prepare command.
        system(cmd);     // execute it.

        return 0;
}

I know its ugly and there are several better ways to do it...but it works :)

codaddict
A: 

You can use the mail command also.

Inside the C program using the mail command and system function you can send the mail to the user.

 system("mail -s subject  address < filename")

  Example
 system ("mail -s test [email protected] < filename")

Note: The file should be exists. If you want to type the content, yiu can type the content inside the file, then send that file to receiver.

muruga