我怎样才能用C发送电子邮件?

meh*_*mak 5 c email

我只是想知道如何使用C发送电子邮件?我用Google搜索了一下,但找不到合适的东西.

Mar*_*ine 7

使用libcurl。它支持 SMTP 和 TLS,以防您需要对发送进行身份验证。他们提供了一些示例 C 代码


cod*_*ict 6

在类似Unix的系统上,您可以使用system,sendmail如下所示:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我知道它的丑陋,并有几种更好的方法来做到这一点......但它的工作原理:)


Bre*_*ers 6

更便携的方法是使用libquickmail ( http://sf.net/p/libquickmail ),它在 GPL 下获得许可。它甚至允许发送附件。

示例代码:

  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 Code Online (Sandbox Code Playgroud)


Mes*_*ssa 2

运行sendmail电子邮件并将其传递到其标准输入(在类 Unix 系统上),或使用某些 SMTP 客户端库连接到 SMTP 邮件服务器。