How to send mail in c

In C, you can send an email using the sendmail command or by using a library that provides email functionality. Here are a few examples:

Using sendmail command:

You can use the system function to execute the sendmail command and send an email. Here's an example:

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

int main() {
    system("sendmail -t < email.txt");
    return 0;
}

In this example, email.txt is a file that contains the email message in the format:

To: [email protected]
Subject: Test email
Hello, this is a test email.

Using a library:

There are several libraries available that provide email functionality in C, such as:

  1. libcurl: A popular library for transferring data over HTTP, including sending emails.
  2. libmail: A library that provides email functionality, including sending and receiving emails.
  3. libesmtp: A library that provides a simple way to send emails using the SMTP protocol.

Here's an example 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_USE_SSL, CURLUSESSL_ALL);
        curl_easy_setopt(curl, CURLOPT_USERNAME, "username");
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "password");
        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, this is a test email.");
        res = curl_easy_perform(curl);
        if(res!= CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    return 0;
}

In this example, we use libcurl to connect to an SMTP server, authenticate, and send an email.

Note: These examples are just a starting point, and you'll likely need to modify them to fit your specific use case. Additionally, you may need to handle errors and exceptions properly.