我只是想知道如何使用 C 发送电子邮件?我用谷歌搜索了一下,但找不到任何合适的东西。
在类 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;
}
我知道它很难看,并且有几种更好的方法可以做到......但它有效:)
更便携的方法是使用 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);
运行
sendmail
并将电子邮件传递到其标准输入(在类 UNIX 系统上),或使用某些 SMTP 客户端库连接到 SMTP 邮件服务器。
最明显的选择:
system()
调用现有的命令行工具来发送邮件。不太可移植(需要具有给定调用语法的外部工具等),但很容易实现。您也可以使用邮件命令。
在C程序中使用mail命令和系统函数可以将邮件发送给用户。
system("mail -s subject address < filename")
Example
system ("mail -s test [email protected] < filename")
注意:该文件应该存在。如果你想输入内容,你可以在文件中输入内容,然后将该文件发送给接收者。
哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈)