使用C语言Curl程序通过Gmail发邮件遇SSL证书错误求助
基于Curl的C程序通过Gmail发送邮件时的SSL证书问题
我想用基于Curl的C语言程序通过Gmail发送邮件,但即便指定了SSL选项,运行时还是出现SSL错误。以下是相关代码、编译脚本和不同尝试下的错误信息:
错误信息
- 初始错误:
SSL peer certificate or SSH remote key was not OK - 将cacert.pem路径设置到
CURLOPT_SSLCERT时,出现:Problem with the local SSL certificate和unable to set private key file: 'cacert.pem' type PEM - 将curl-ca-bundle.crt路径设置到该选项时,出现类似的本地SSL证书问题和私钥文件错误
C语言代码
#include <stdio.h> #include <curl/curl.h> static size_t payload_source(char *ptr, size_t size, size_t nmemb, void *userp); typedef struct { size_t bytes_read; } upload_status; char *from_addr = "<sender@gmail.com>"; char *to_addr = "<receiver@gmail.com>"; static const char *payload_text = "To: " "<receiver@gmail.com>" "\r\n" "From: " "<sender@gmail.com>" "\r\n" "Cc: " "" "\r\n" //"Message-ID: <dcd7cb36-11db-487a-9f3a-e652a9458efd@" //"rfcpedant.example.org>\r\n" "Subject: SMTP example message\r\n" "\r\n" /* empty line to divide headers from body, see RFC 5322 */ "This message is a test\r\n" "\r\n" "It could be a lot of lines, could be MIME encoded, whatever.\r\n" "Check RFC 5322.\r\n"; int main(void) { CURL *curl; CURLcode res = CURLE_OK; struct curl_slist *recipients = NULL; upload_status upload = { 0 }; printf("This is a curl program\n"); curl = curl_easy_init(); if(!curl) { printf("Curl wasn't initialized!\n"); return 1; } printf("Curl was initialized!\n"); curl_easy_setopt(curl, CURLOPT_URL, "smtps://smtp.gmail.com:465"); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); curl_easy_setopt(curl, CURLOPT_MAIL_FROM, from_addr); recipients = curl_slist_append(recipients, to_addr); curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients); curl_easy_setopt(curl, CURLOPT_USE_SSL, 1L); curl_easy_setopt(curl, CURLOPT_USERNAME, from_addr); curl_easy_setopt(curl, CURLOPT_PASSWORD, "password"); curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source); curl_easy_setopt(curl, CURLOPT_READDATA, &upload); curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_ANY); printf("Sending email...\n"); res = curl_easy_perform(curl); printf("%d %d\n", (int)res, (int)CURLE_OK); if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); curl_slist_free_all(recipients); curl_easy_cleanup(curl); return (int)res; } static size_t payload_source(char *ptr, size_t size, size_t nmemb, void *userp) { upload_status *upload_ctx = (upload_status *)userp; const char *data; size_t room = size * nmemb; if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) { return 0; } data = &payload_text[upload_ctx->bytes_read]; if(data) { size_t len = strlen(data); if(room < len) len = room; memcpy(ptr, data, len); upload_ctx->bytes_read += len; return len; } return 0; }
编译脚本run.bat
@echo off del main.exe cls gcc -I src/include -L src/lib -o main *.c -lcurl -lssl -lssh2 -lbrotlicommon -lbrotlidec -lcrypto -lnghttp2 -lnghttp3 -lngtcp2_crypto_quictls -lngtcp2 -lz -lzstd main
内容的提问来源于stack exchange,提问作者Artiom Kvartiuk
相关产品推荐
相关产品推荐

