我的目标是通过 Curl C 程序用 gmail 发送电子邮件。每当我运行此命令时,即使我指定了使用 SSL 的选项,我也会收到 SSL 错误
#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 = "<[email protected]>";
char *to_addr = "<[email protected]>";
static const char *payload_text =
"To: " "<[email protected]>" "\r\n"
"From: " "<[email protected]>" "\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;
}
我从这段代码中得到的错误消息是:“SSL 对等证书或 SSH 远程密钥不正常”
如果我将 cacert.pem 的路径添加到 CURLOPT_SSLCERT,我会得到:“本地 SSL 证书出现问题”和“无法设置私钥文件:‘cacert.pem’类型 PEM”
如果我将路径添加到curl-ca-bundle.crt,我会得到:“本地SSL证书有问题”和“无法设置私钥文件:'cert.crt'类型PEM”
我相信谷歌不再允许使用没有令牌(API)的基本身份验证。
愿本主题对您有所帮助: curl 可以不再使用 gmail 帐户发送电子邮件吗?