在类似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)
我知道它的丑陋,并有几种更好的方法来做到这一点......但它的工作原理:)
更便携的方法是使用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)