【发布时间】:2022-08-15 06:41:01
【问题描述】:
希望你们一切都好。
我正在尝试制作一个使用 Gmail 发送电子邮件的程序。
我有这个命令可以在 CMD 中完美运行,但我不知道如何让它在应用程序中运行。
这是命令:
curl smtps://smtp.gmail.com:465 -v --mail-from \"<sir@gmail.com>\" --mail-rcpt \"<mister@gmail.com>\" --ssl -u sir@gmail.com:password -T \"mail.txt\" -k --anyauth
这些是 mail.txt 的内容:
From: \"Sir\" <sir@gmail.com>
To: \"Mister\" <mister@gmail.com>
Subject: This is a test
Hi,
I’m sending this mail with curl thru my gmail account.
Bye!
我在cURL wesite 上遵循了这个例子
这就是我得到的:
static const char* payload_text[] = {
\"From:<sir@gmail.com>\\n\"
\"To:<mister@gmail.com>\\n\"
\"Subject : This is a test\\n\\r\"
\"Hi,\\n\"
\"I’m sending this mail with curl thru my gmail account.\\n\"
\"Bye!\\n\"
};
struct upload_status {
int lines_read;
};
static size_t payload_source(void* ptr, size_t size, size_t nmemb, void* userp)
{
struct upload_status* upload_ctx = (struct upload_status*)userp;
const char* data;
if ((size == 0) || (nmemb == 0) || ((size * nmemb) < 1)) {
return 0;
}
data = payload_text[upload_ctx->lines_read];
if (data) {
size_t len = strlen(data);
memcpy(ptr, data, len);
upload_ctx->lines_read++;
return len;
}
return 0;
}
int curl_send_email()
{
CURL* curl;
CURLcode res = CURLE_OK;
struct curl_slist* recipients = NULL;
struct upload_status upload_ctx = { 0 };
curl = curl_easy_init();
if (curl)
{
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, \"<sir@gmail.com>\");
recipients = curl_slist_append(recipients, \"<mister@gmail.com>\");
curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);
curl_easy_setopt(curl, CURLOPT_USE_SSL, 1L);
curl_easy_setopt(curl, CURLOPT_USERNAME, \"<sir@gmail.com>\");
curl_easy_setopt(curl, CURLOPT_PASSWORD, \"password\");
curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);
curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_ANY);
/* Send the message */
res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK)
fprintf(stderr, \"curl_easy_perform() failed: %s\\n\",
curl_easy_strerror(res));
/* Free the list of recipients */
curl_slist_free_all(recipients);
curl_easy_cleanup(curl);
}
return (int)res;
}
int main()
{
int message = curl_send_email();
std::cout << message << std::endl;
return 0;
}
但它不起作用,它返回一条消息说“登录失败”,即使用户名和密码是正确的。
有人可以告诉我我做错了什么吗?
提前致谢。
-
无关:
curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, \"<mister@gmail.com>\");应该使用您在上面创建的slistrecipients,如果我没记错的话。 -
您的 Google 帐户是否配置为允许不安全的登录?
-
嗨,泰德,哦,是的,对不起,这是我在替换原始地址时打错了字。
-
嗨艾伦,是的,它被配置为允许不安全的登录。
-
你所有的行尾都应该是
\"\\r\\n\"。