开发者

How can I send e-mail in C?

I'm just wondering how can I send email using C? I Googled it a little bit, b开发者_运维知识库ut could not find anything proper.


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[] = "sample@example.com"; // 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 :)


Use libcurl. It supports SMTP and also TLS, in case you need to authenticate for sending. They offer some example C code.


A more portable way is to use libquickmail (http://sf.net/p/libquickmail), licensed under GPL. It even allows sending attachments.

Example code:

  quickmail_initialize();
  quickmail mailobj = quickmail_create(FROM, "libquickmail test e-mail");
  quickmail_set_body(mailobj, "This is a test e-mail.\nThis mail was sent using libquickmail.");
  quickmail_add_attachment_file(mailobj, "attachment.zip", NULL);
  const char* errmsg;
  if ((errmsg = quickmail_send(mailobj, SMTPSERVER, SMTPPORT, SMTPUSER, SMTPPASS)) != NULL)
    fprintf(stderr, "Error sending e-mail: %s\n", errmsg);
  quickmail_destroy(mailobj);


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.


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.


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 hello@gmail.com < 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜