我有一个简单的 C++ 发送电子邮件应用程序,但是当我运行它时,我有链接错误。问题是什么?另一个问题,错误是否与主机名参数有关?我将其设置为“smtp.google.com”?
#include "io.h"
#include "winsock2.h" /* WSAGetLastError, WSAStartUp */
#include <iostream>
using namespace std;
#define snprintf _snprintf
static void sendmail_write(
const int sock,
const char *str,
const char *arg
) {
char buf[4096];
if (arg != NULL)
snprintf(buf, sizeof(buf), str, arg);
else
snprintf(buf, sizeof(buf), str);
send(sock, buf, strlen(buf), 0);
}
static int sendmail(
const char *from,
const char *to,
const char *subject,
const char *body,
const char *hostname,
const int port
) {
struct hostent *host;
struct sockaddr_in saddr_in;
int sock = 0;
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
return -1;
}
sock = socket(AF_INET, SOCK_STREAM, 0);
host = gethostbyname(hostname);
saddr_in.sin_family = AF_INET;
saddr_in.sin_port = htons((u_short)port);
saddr_in.sin_addr.s_addr = 0;
memcpy((char*)&(saddr_in.sin_addr), host->h_addr, host->h_length);
if (connect(sock, (struct sockaddr*)&saddr_in, sizeof(saddr_in)) == -1) {
return -2;
}
sendmail_write(sock, "HELO %s\n", from); // greeting
sendmail_write(sock, "MAIL FROM: %s\n", from); // from
sendmail_write(sock, "RCPT TO: %s\n", to); // to
sendmail_write(sock, "DATA\n", NULL); // begin data
// next comes mail headers
sendmail_write(sock, "From: %s\n", from);
sendmail_write(sock, "To: %s\n", to);
sendmail_write(sock, "Subject: %s\n", subject);
sendmail_write(sock, "\n", NULL);
sendmail_write(sock, "%s\n", body); // data
sendmail_write(sock, ".\n", NULL); // end data
sendmail_write(sock, "QUIT\n", NULL); // terminate
close(sock);
return 0;
}
int main(int argc, char *argv[]) {
int ret = sendmail(
"someone@gmail.com", // from
"someone@gmail.com", // to
"Subject",
"body",
"smtp.google.com",
25
);
if (ret != 0)
cout<< "Failed to send mail (code: %i).\n";
else
cout<<"Mail successfully sent.\n";
return ret;
}
我的错误是这样的:
错误 LNK2019:函数“int __cdecl sendmail(char const *,char const *,char const *,char const *,char const *,int)”(?sendmail@@YAHPBD0000H@Z) 中引用了未解析的外部符号 __imp__connect@12
我尝试了“smtp.gmail.com”,现在也不例外,但它显示“邮件已成功发送”,而我在收件箱中看不到任何电子邮件。任何想法?