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

时间:2010-03-02 12:20:09

标签: c email

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

6 个答案:

答案 0 :(得分:5)

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

#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;
}

我知道它的丑陋,有几种更好的方法可以做到......但它有效:)

答案 1 :(得分:4)

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

答案 2 :(得分:3)

最明显的选择:

  1. 使用system()调用现有的命令行工具来发送邮件。不是非常便携(需要具有给定调用语法的外部工具等),但很容易实现。
  2. 使用一些图书馆。
  3. 自己实施SMTP,直接与邮件服务器对话。很多工作。

答案 3 :(得分:2)

您也可以使用mail命令。

使用mail命令和系统功能在C程序中,您可以将邮件发送给用户。

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

  Example
 system ("mail -s test hello@gmail.com < filename")

注意:该文件应该存在。如果要输入内容,yiu可以在文件中键入内容,然后将该文件发送给接收者。

答案 4 :(得分:2)

更便携的方式是使用GPL授权的 libquickmail http://sf.net/p/libquickmail)。 它甚至允许发送附件。

示例代码:

  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);

答案 5 :(得分:1)

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

相关问题