Attach pdf file in mail in c

To attach a PDF file to an email in C, you'll need to use a library that allows you to create and send emails, as well as attach files. Here's an example using the libcurl and libssl libraries:

Note: This example assumes you have the libcurl and libssl libraries installed on your system.

Example code:

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

int main() {
    // Set up the email details
    const char* from = "[email protected]";
    const char* to = "[email protected]";
    const char* subject = "Test email with attachment";
    const char* body = "This is a test email with a PDF attachment.";

    // Set up the PDF file
    const char* pdf_file = "path/to/your/pdf/file.pdf";

    // Initialize the curl session
    CURL *curl;
    CURLcode res;
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if(curl) {
        // Set the email headers
        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, from);
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "your_email_password");
        curl_easy_setopt(curl, CURLOPT_MAIL_FROM, from);
        curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, to);

        // Set the email body
        curl_easy_setopt(curl, CURLOPT_READDATA, body);
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);

        // Attach the PDF file
        curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
        curl_easy_setopt(curl, CURLOPT_INFILE, pdf_file);
        curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)sizeof(*pdf_file));

        // Send the email
        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;
}

Explanation:

  1. We include the necessary headers for libcurl and libssl.
  2. We set up the email details, including the sender, recipient, subject, and body.
  3. We set up the PDF file to be attached.
  4. We initialize the curl session using curl_global_init and curl_easy_init.
  5. We set the email headers using curl_easy_setopt.
  6. We set the email body using curl_easy_setopt.
  7. We attach the PDF file using curl_easy_setopt.
  8. We send the email using curl_easy_perform.
  9. We clean up the curl session using curl_easy_cleanup and curl_global_cleanup.

Note: This is just a basic example, and you may need to modify it to fit your specific use case. Additionally, you'll need to replace the placeholders ([email protected], [email protected], path/to/your/pdf/file.pdf, etc.) with your actual email details and PDF file path.