使用C++WINSOCK(TCP、SSL)发送电子邮件



几天来,我一直在尝试用C++给自己发送一封简短的纯文本电子邮件。我正在使用Visual Studio Express 2015。我最终希望能通过电子邮件自动提醒自己。我使用的是Gmail帐户。我似乎没办法把它发挥作用。我可以发送数据,但无法接收。服务器正在关闭我的连接,出现错误10054。(你可以在这个页面上阅读这个错误的含义。)

历史是这样的:我从很多S.O.的帖子和MSDN的文章中拼凑出了这一切。我曾经在这段代码中有一个功能性的WSASetSocketSecurity部分,但无论出于什么原因,我的连接尝试都超时了,所以我省略了它。在这一点上,当我发送EHLO或HELO时,我会接受服务器不切断我的连接。

我真的不知道该怎么办。几天的探索,几十篇阅读文章,数百条死胡同。我希望你能原谅那些垃圾代码,以及S.O.删除了我的手动对齐。请看一看,让我知道我做错了什么,让我了解任何不恰当的风格,或者任何其他冒犯你优秀程序员情感的东西。非常感谢。

#include "stdafx.h"
#include <exception>
#include <string>
#include <iostream> // In-out stream objects for development
#include <stdio.h> // Standard in-out for development
#include <winsock2.h> // For making socket connection to email server
#include <Mstcpip.h>
#include <Ws2tcpip.h> // Enhanced protocols to assist winsock2.h
#pragma comment(lib, "Ws2_32.lib") // Library for winsock2.h
#pragma comment(lib, "Fwpuclnt.lib") // Library for winsock2.h
#define BUFFER_SIZE 512
using namespace std;
void cleanup(SOCKET ConnectSocket, struct addrinfo *result) {
    if (ConnectSocket != INVALID_SOCKET) {
        closesocket(ConnectSocket);
    }
    freeaddrinfo(result);
    WSACleanup();
    cout << "socket closed" << endl;
    cin.get(); // Development only
}
int _tmain(int argc, char* argv[]) {
    // Initialize email parameters
    char            bccAddresses[64] = "";
    char            fromAddress[64] = "my_email@host.com";
    char            msg[512] = "Hello world!";
    char            port[12] = "465";
    char            serverName[64] = "smtp.host.com";
    char            toAddresses[64] = "my_email@host.com";
    SOCKET          ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL;
    struct addrinfo *ptr = NULL;
    struct addrinfo hints;
    WSADATA         wsaData;
    try {
        // Initialize Winsock
        int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
        if (iResult == SOCKET_ERROR) {
            cout << "Error " << iResult << endl;
            throw std::exception("WSAStartup failedn");
        }
        cout << "WSAStartup successful: " << iResult << endl;
        // Set up the hints socket address structure
        ZeroMemory(&hints, sizeof(hints));
        hints.ai_flags = AI_SECURE;
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_TCP;
        // Resolve the server address and port
        iResult = getaddrinfo(serverName, port, &hints, &result);
        if (iResult == SOCKET_ERROR) {
            cout << "Error " << WSAGetLastError() << endl;
            throw std::exception("getaddrinfo failedn");
        }
        cout << "getaddrinfo successful: " << iResult << endl;
        // Connect to the socket
        ptr = result;
        ConnectSocket = WSASocket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol, NULL, 0, 0);
        if (ConnectSocket == INVALID_SOCKET) {
            cout << "Error " << WSAGetLastError() << endl;
            throw std::exception("Error at socketn");
        }
        cout << "WSASocket successful: " << iResult << endl;
        // Connect via the socket
        iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (iResult == SOCKET_ERROR) {
            cout << "Error " << WSAGetLastError() << endl;
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            throw std::exception("Unable to connect to server!n");
        }
        cout << "connect successful: " << iResult << endl;
        // Send message
        char sendBuffer[BUFFER_SIZE] = "What is your malfunction";
        char recvBuffer[BUFFER_SIZE];
        sprintf_s(sendBuffer, BUFFER_SIZE, "EHLO %s%s", serverName, "rn");
        iResult = send(ConnectSocket, sendBuffer, BUFFER_SIZE, 0);
        if (iResult == SOCKET_ERROR) {
            cout << "Error " << WSAGetLastError() << endl;
            throw std::exception("WINSOCK send failedn");
        }
        cout << "Sent:n" << sendBuffer << "Byte count: " << iResult << endl;
        iResult = recv(ConnectSocket, recvBuffer, BUFFER_SIZE, 0);
        if (iResult == SOCKET_ERROR) {
            cout << "Error " << WSAGetLastError() << endl;
            throw std::exception("WINSOCK recv failedn");
        }
        cout << "EHLO response: " << iResult << endl;
        sprintf_s(sendBuffer, BUFFER_SIZE, "QUIT%s", "rn");
        iResult = send(ConnectSocket, sendBuffer, BUFFER_SIZE, 0);
        if (iResult == SOCKET_ERROR) {
            cout << "Error " << WSAGetLastError() << endl;
            throw std::exception("WINSOCK send failedn");
        }
        cout << "Sent:n" << sendBuffer << "Byte count: " << iResult << endl;
        iResult = recv(ConnectSocket, recvBuffer, BUFFER_SIZE, 0);
        if (iResult < 0) {
            cout << "Error " << WSAGetLastError() << endl;
            throw std::exception("WINSOCK recv failedn");
        }
        cout << "Quit response: " << iResult << endl;
        // Shutdown the connection
        iResult = shutdown(ConnectSocket, SD_SEND);
        if (iResult == SOCKET_ERROR) {
            cout << "Error " << WSAGetLastError() << endl;
            throw std::exception("shutdown failedn");
        }
        // Clean up
        cleanup(ConnectSocket, result);
        return 0;
    }
    catch (std::exception err) {
        printf(err.what());
        cleanup(ConnectSocket, result);
        return 1;
    }
    catch (...) {
        printf("Unknown errorn");
        cleanup(ConnectSocket, result);
        return 2;
    }
}

这个答案的三个部分。

  1. MIME对用户名和密码进行编码
  2. 实际发送用户名和密码!:)
  3. 有些服务器持怀疑态度,希望您说两次HELO或EHLO

我将很快发布完整的代码。尽管我觉得我已经完成了40%的工作,但我的成功要归功于这个网站:http://www.coastrd.com/smtps.

相关内容

  • 没有找到相关文章

最新更新