Smtp client hangs after sending data

问题内容:

I want to build an stmp client using c++ for learning purposes.
After I managed to implement the initial connection + auth login I am stuck on sending the message after using the data command.

Here is my code

     void sendmail()
     {

            write_command("MAIL FROM: <foo@bar.de>");
            write_command("RCPT TO: <bar.foo@baz.de>");
            write_command("DATA");
            write_command("Subject: testmail"); // HANGS here after data command
            write_command("BlaBlub");
            write_command(" ");
            write_command(".");
            write_command("QUIT");
     }

    void write_command(std::string command)
    {
        ssize_t n;
        empty_buffer();
        command += '\r';
        command += '\n';
        char command_buffer[255];
        strcpy(command_buffer, command.c_str());
        n = write(sockfd,command_buffer,strlen(command_buffer));
        if (n < 0){
            error("ERROR writing to socket");
        }
        n = read_to_buffer();
        if (n < 0) {
            error("ERROR reading from socket");
        }
        printf("%s\n",this->buffer);
    }

I’m using smtp.mailtrap.io on port 25.

Here is a gist with the full class https://gist.github.com/xhallix/7f2d87a8b2eab4953d161059c2482b37

Here is the server output

Starting smpt client 
220 mailtrap.io ESMTP ready

250-mailtrap.io
250-SIZE 5242880
250-PIPELINING
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250-AUTH PLAIN LOGIN CRAM-MD5
250 STARTTLS

334 VXNlcm5hbWU6

334 UGFzc3dvcmQ6

235 2.0.0 OK

250 2.1.0 Ok

250 2.1.0 Ok

354 Go ahead
(HANGS HERE)

Thanks for helping me out

问题评论:

答案:

答案1:

DATA command expects the whole mail message, as shown here. The write_command() sends each line of the mail and then expects the response. Since the server returns the response once the mail message is finished (after empty line and dot), it stays in the hanging mode after the first message line. This code snippet can be helpful for your case.

BTW, you should put an empty line between the mail header and body, which I guess is after the subject line. Also, it might happen that the server rejects the message without the From and To headers.

答案评论:

    
thank you I will try to change this
– abdoe
41 mins ago
    
great! thank you!
– abdoe
34 mins ago

原文地址:

https://stackoverflow.com/questions/47755099/smtp-client-hangs-after-sending-data

添加评论