C++ send zip file using google email with curl

  attachment, c++, curl, email

I’m using c++ and curl for sending an email with attachments, a zip archive in this example. I receive the email on gmail but when I download the .zip if I try to extract the content with WinRar I got the error:

The archive is either in unknown format or damaged

The zip is okay, I can extract it before sending.

This is the function for sending the file:

int sendFile()
{
    CURL *curl;
    CURLcode res = CURLE_OK;

    curl = curl_easy_init();
    if(curl) {
        struct curl_slist *headers = NULL;
        struct curl_slist *recipients = NULL;
        struct curl_slist *slist = NULL;
        curl_mime *mime;
        curl_mime *alt;
        curl_mimepart *part;
        const char **cpp;

        /* This is the URL for your mailserver */
        curl_easy_setopt(curl, CURLOPT_URL, "smtps://smtp.gmail.com:465");


        curl_easy_setopt(curl, CURLOPT_USERNAME, "email");
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "password");
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);

      
        curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM_ADDR);

      
        recipients = curl_slist_append(recipients, TO_ADDR);
        recipients = curl_slist_append(recipients, CC_ADDR);
        curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);

        for(cpp = headers_text; *cpp; cpp++)
            headers = curl_slist_append(headers, *cpp);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        mime = curl_mime_init(curl);

        alt = curl_mime_init(curl);

        /* Text message. */
        part = curl_mime_addpart(alt);
        curl_mime_data(part, inline_text, CURL_ZERO_TERMINATED);
        part = curl_mime_addpart(mime);
        curl_mime_subparts(part, alt);
        curl_mime_type(part, "multipart/alternative");
        slist = curl_slist_append(NULL, "Content-Disposition: inline");
        curl_mime_headers(part, slist, 1);
        
        /* File */
        std::string attachment = "D:/report.zip";
        part = curl_mime_addpart(mime);
        curl_mime_type(part, "application/zip");
        curl_mime_filedata(part, attachment.c_str());
        curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime);

        res = curl_easy_perform(curl);

        if(res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %sn",
                    curl_easy_strerror(res));

        curl_slist_free_all(recipients);
        curl_slist_free_all(headers);

        curl_easy_cleanup(curl);

        curl_mime_free(mime);
    }

    return (int)res;
}

Can you help me to understand what’ s wrong? The zip is in the email but I can’ t open it once downloaded because is damaged.

Thank you!

Source: Windows Questions C++

LEAVE A COMMENT