如何用C语言发送电子邮件?

问题描述 投票:0回答:7

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

c email
7个回答
13
投票

在类 Unix 系统上,您可以使用

system
sendmail
,如下所示:

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

我知道它很难看,并且有几种更好的方法可以做到......但它有效:)


11
投票

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


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

2
投票

运行

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


2
投票

最明显的选择:

  1. 使用
    system()
    调用现有的命令行工具来发送邮件。不太可移植(需要具有给定调用语法的外部工具等),但很容易实现。
  2. 使用一些库。
  3. 自己实现SMTP,并直接与邮件服务器通信。工作量很大。

2
投票

您也可以使用邮件命令。

在C程序中使用mail命令和系统函数可以将邮件发送给用户。

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

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

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


-3
投票

哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈)

© www.soinside.com 2019 - 2024. All rights reserved.