C send mail without credentials

A classic question!

In C, you can send an email without credentials using the sendmail command or a library like libcurl. Here are some examples:

Using sendmail command:

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *fp = popen("sendmail -t -i -f [email protected] -c 'Subject: Test email' 'Hello, world!'","w");
    if (fp == NULL) {
        perror("popen");
        return 1;
    }
    fprintf(fp, "To: [email protected]\n");
    fprintf(fp, "From: [email protected]\n");
    fprintf(fp, "Subject: Test email\n");
    fprintf(fp, "Hello, world!\n");
    fclose(fp);
    return 0;
}

This code uses the popen function to execute the sendmail command with the -t option, which tells sendmail to read the email message from standard input. The -i option tells sendmail to ignore the From header, and the -f option specifies the sender's email address. The email message is written to standard output using fprintf.

Using libcurl:

#include <curl/curl.h>
#include <stdio.h>

int main() {
    CURL *curl;
    CURLcode res;

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.example.com");
        curl_easy_setopt(curl, CURLOPT_MAIL_FROM, "[email protected]");
        curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, "[email protected]");
        curl_easy_setopt(curl, CURLOPT_READDATA, "Hello, world!");
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
        res = curl_easy_perform(curl);
        if(res!= CURLE_OK) {
            fprintf(stderr, "cURL error: %s\n", curl_easy_strerror(res));
        }
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    return 0;
}

This code uses the libcurl library to send an email using the SMTP protocol. The curl_easy_setopt function is used to set various options, including the URL of the SMTP server, the sender's email address, the recipient's email address, and the email message. The curl_easy_perform function is used to send the email, and the curl_easy_strerror function is used to get the error message if the email fails to send.

Note that both of these examples assume that you have a working SMTP server and that the email message is simple text. In a real-world application, you would likely want to handle errors and exceptions more robustly, and you may need to use a more advanced email library or framework.