C send mail
A classic!
To send an email using C, you can use the sendmail
command or the libmail
library. Here's an example of how to send an email using sendmail
:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp;
char buffer[1024];
char *cmd = "sendmail -v -t";
fp = popen(cmd, "w");
if (fp == NULL) {
printf("Could not open pipe to sendmail\n");
return 1;
}
// Write the email headers
fprintf(fp, "To: [email protected]\n");
fprintf(fp, "From: [email protected]\n");
fprintf(fp, "Subject: Test email from C program\n");
fprintf(fp, "MIME-Version: 1.0\n");
fprintf(fp, "Content-Type: text/plain; charset=UTF-8\n\n");
// Write the email body
fprintf(fp, "This is a test email sent from a C program.\n");
fprintf(fp, "It's a great day to send emails!\n");
// Close the pipe
pclose(fp);
return 0;
}
This code uses the popen
function to open a pipe to the sendmail
command, and then writes the email headers and body to the pipe using fprintf
. Finally, it closes the pipe using pclose
.
Alternatively, you can use the libmail
library, which provides a more convenient API for sending emails. Here's an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libmail.h>
int main() {
Mail *mail;
MailMessage *message;
MailRecipient *recipient;
// Create a new mail object
mail = mail_new();
// Create a new message object
message = mail_message_new(mail);
// Set the message subject
mail_message_set_subject(message, "Test email from C program");
// Set the message body
mail_message_set_body(message, "This is a test email sent from a C program.\n");
mail_message_set_body(message, "It's a great day to send emails!");
// Add a recipient to the message
recipient = mail_recipient_new();
mail_recipient_set_address(recipient, "[email protected]");
mail_message_add_recipient(message, recipient);
// Send the message
mail_send(mail, message);
// Clean up
mail_message_free(message);
mail_recipient_free(recipient);
mail_free(mail);
return 0;
}
This code creates a new Mail
object, a new MailMessage
object, and a new MailRecipient
object. It sets the message subject, body, and recipient, and then sends the message using the mail_send
function. Finally, it cleans up by freeing the objects.
Note that you'll need to install the libmail
library and link against it when compiling your program.