SmtpClient-for-Qt/src/smtpclient.cpp

499 lines
12 KiB
C++
Raw Normal View History

2011-08-30 18:59:16 +00:00
/*
2012-07-24 14:06:55 +00:00
Copyright (c) 2011-2012 - Tőkés Attila
2011-08-30 18:59:16 +00:00
2011-09-02 12:20:33 +00:00
This file is part of SmtpClient for Qt.
2012-07-24 14:06:55 +00:00
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
2011-09-02 12:20:33 +00:00
2012-07-24 14:06:55 +00:00
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
2011-09-02 12:20:33 +00:00
2011-09-02 15:24:39 +00:00
See the LICENSE file for more details.
2011-08-30 18:59:16 +00:00
*/
#include "smtpclient.h"
#include <QFileInfo>
#include <QByteArray>
/* [1] Constructors and destructors */
SmtpClient::SmtpClient(const QString & host, int port, ConnectionType connectionType) :
2015-10-26 15:31:51 +00:00
socket(NULL),
name("localhost"),
2011-08-30 18:59:16 +00:00
authMethod(AuthPlain),
connectionTimeout(5000),
responseTimeout(5000),
2015-10-26 15:31:51 +00:00
sendMessageTimeout(60000)
2011-08-30 18:59:16 +00:00
{
setConnectionType(connectionType);
2011-08-30 18:59:16 +00:00
this->host = host;
this->port = port;
connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(socketError(QAbstractSocket::SocketError)));
connect(socket, SIGNAL(readyRead()),
this, SLOT(socketReadyRead()));
}
2015-06-03 20:27:54 +00:00
SmtpClient::~SmtpClient() {
if (socket)
delete socket;
}
2011-08-30 18:59:16 +00:00
/* [1] --- */
/* [2] Getters and Setters */
void SmtpClient::setUser(const QString &user)
{
this->user = user;
}
void SmtpClient::setPassword(const QString &password)
{
this->password = password;
}
void SmtpClient::setAuthMethod(AuthMethod method)
{
this->authMethod = method;
}
2014-11-01 20:50:37 +00:00
void SmtpClient::setHost(const QString &host)
2011-08-30 18:59:16 +00:00
{
this->host = host;
}
void SmtpClient::setPort(int port)
{
this->port = port;
}
void SmtpClient::setConnectionType(ConnectionType ct)
{
this->connectionType = ct;
2011-08-30 18:59:16 +00:00
2015-06-03 20:27:54 +00:00
if (socket)
delete socket;
switch (connectionType)
{
case TcpConnection:
2011-08-30 18:59:16 +00:00
socket = new QTcpSocket(this);
break;
case SslConnection:
case TlsConnection:
2011-08-30 18:59:16 +00:00
socket = new QSslSocket(this);
}
2011-08-30 18:59:16 +00:00
}
const QString& SmtpClient::getHost() const
{
return this->host;
}
const QString& SmtpClient::getUser() const
{
return this->user;
}
const QString& SmtpClient::getPassword() const
{
return this->password;
}
SmtpClient::AuthMethod SmtpClient::getAuthMethod() const
{
return this->authMethod;
}
int SmtpClient::getPort() const
{
return this->port;
}
SmtpClient::ConnectionType SmtpClient::getConnectionType() const
{
return connectionType;
2011-08-30 18:59:16 +00:00
}
const QString& SmtpClient::getName() const
{
return this->name;
}
void SmtpClient::setName(const QString &name)
{
this->name = name;
}
const QString & SmtpClient::getResponseText() const
{
return responseText;
}
int SmtpClient::getResponseCode() const
{
return responseCode;
}
QTcpSocket* SmtpClient::getSocket() {
return socket;
}
int SmtpClient::getConnectionTimeout() const
{
return connectionTimeout;
}
void SmtpClient::setConnectionTimeout(int msec)
{
connectionTimeout = msec;
}
int SmtpClient::getResponseTimeout() const
{
return responseTimeout;
}
void SmtpClient::setResponseTimeout(int msec)
{
responseTimeout = msec;
}
int SmtpClient::getSendMessageTimeout() const
{
return sendMessageTimeout;
}
void SmtpClient::setSendMessageTimeout(int msec)
{
sendMessageTimeout = msec;
}
2011-08-30 18:59:16 +00:00
/* [2] --- */
/* [3] Public methods */
bool SmtpClient::connectToHost()
{
switch (connectionType)
{
case TlsConnection:
case TcpConnection:
2011-08-30 18:59:16 +00:00
socket->connectToHost(host, port);
break;
case SslConnection:
((QSslSocket*) socket)->connectToHostEncrypted(host, port);
break;
}
2011-08-30 18:59:16 +00:00
// Tries to connect to server
if (!socket->waitForConnected(connectionTimeout))
{
emit smtpError(ConnectionTimeoutError);
return false;
}
try
{
// Wait for the server's response
waitForResponse();
// If the response code is not 220 (Service ready)
// means that is something wrong with the server
if (responseCode != 220)
{
emit smtpError(ServerError);
return false;
}
// Send a EHLO/HELO message to the server
// The client's first command must be EHLO/HELO
sendMessage("EHLO " + name);
2011-08-30 18:59:16 +00:00
// Wait for the server's response
waitForResponse();
// The response code needs to be 250.
if (responseCode != 250) {
2011-08-30 18:59:16 +00:00
emit smtpError(ServerError);
return false;
}
if (connectionType == TlsConnection) {
// send a request to start TLS handshake
sendMessage("STARTTLS");
// Wait for the server's response
waitForResponse();
// The response code needs to be 220.
if (responseCode != 220) {
emit smtpError(ServerError);
return false;
};
((QSslSocket*) socket)->startClientEncryption();
if (!((QSslSocket*) socket)->waitForEncrypted(connectionTimeout)) {
qDebug() << ((QSslSocket*) socket)->errorString();
emit smtpError(ConnectionTimeoutError);
return false;
}
// Send ELHO one more time
sendMessage("EHLO " + name);
// Wait for the server's response
waitForResponse();
// The response code needs to be 250.
if (responseCode != 250) {
emit smtpError(ServerError);
return false;
}
}
2011-08-30 18:59:16 +00:00
}
catch (ResponseTimeoutException)
{
return false;
}
catch (SendMessageTimeoutException)
{
return false;
}
2011-08-30 18:59:16 +00:00
// If no errors occured the function returns true.
return true;
}
bool SmtpClient::login()
{
return login(user, password, authMethod);
}
bool SmtpClient::login(const QString &user, const QString &password, AuthMethod method)
{
try {
if (method == AuthPlain)
{
// Sending command: AUTH PLAIN base64('\0' + username + '\0' + password)
sendMessage("AUTH PLAIN " + QByteArray().append((char) 0).append(user).append((char) 0).append(password).toBase64());
// Wait for the server's response
waitForResponse();
2011-09-08 17:11:36 +00:00
// If the response is not 235 then the authentication was faild
2011-08-30 18:59:16 +00:00
if (responseCode != 235)
{
2011-09-08 17:11:36 +00:00
emit smtpError(AuthenticationFailedError);
2011-08-30 18:59:16 +00:00
return false;
}
}
else if (method == AuthLogin)
{
// Sending command: AUTH LOGIN
sendMessage("AUTH LOGIN");
// Wait for 334 response code
waitForResponse();
2011-09-08 17:11:36 +00:00
if (responseCode != 334) { emit smtpError(AuthenticationFailedError); return false; }
2011-08-30 18:59:16 +00:00
// Send the username in base64
sendMessage(QByteArray().append(user).toBase64());
// Wait for 334
waitForResponse();
2011-09-08 17:11:36 +00:00
if (responseCode != 334) { emit smtpError(AuthenticationFailedError); return false; }
2011-08-30 18:59:16 +00:00
// Send the password in base64
sendMessage(QByteArray().append(password).toBase64());
// Wait for the server's responce
waitForResponse();
2011-09-08 17:11:36 +00:00
// If the response is not 235 then the authentication was faild
2011-08-30 18:59:16 +00:00
if (responseCode != 235)
{
2011-09-08 17:11:36 +00:00
emit smtpError(AuthenticationFailedError);
2011-08-30 18:59:16 +00:00
return false;
}
}
}
2015-10-26 15:31:51 +00:00
catch (ResponseTimeoutException)
2011-08-30 18:59:16 +00:00
{
// Responce Timeout exceeded
2011-09-08 17:11:36 +00:00
emit smtpError(AuthenticationFailedError);
2011-08-30 18:59:16 +00:00
return false;
}
catch (SendMessageTimeoutException)
{
// Send Timeout exceeded
emit smtpError(AuthenticationFailedError);
return false;
}
2011-08-30 18:59:16 +00:00
return true;
}
bool SmtpClient::sendMail(MimeMessage& email)
{
try
{
// Send the MAIL command with the sender
sendMessage("MAIL FROM: <" + email.getSender().getAddress() + ">");
waitForResponse();
if (responseCode != 250) return false;
// Send RCPT command for each recipient
2012-07-23 18:01:08 +00:00
QList<EmailAddress*>::const_iterator it, itEnd;
// To (primary recipients)
for (it = email.getRecipients().begin(), itEnd = email.getRecipients().end();
it != itEnd; ++it)
sendMessage("RCPT TO:<" + (*it)->getAddress() + ">");
2012-07-23 18:01:08 +00:00
waitForResponse();
if (responseCode != 250) return false;
}
// Cc (carbon copy)
for (it = email.getRecipients(MimeMessage::Cc).begin(), itEnd = email.getRecipients(MimeMessage::Cc).end();
it != itEnd; ++it)
{
sendMessage("RCPT TO:<" + (*it)->getAddress() + ">");
2012-07-23 18:01:08 +00:00
waitForResponse();
if (responseCode != 250) return false;
}
// Bcc (blind carbon copy)
for (it = email.getRecipients(MimeMessage::Bcc).begin(), itEnd = email.getRecipients(MimeMessage::Bcc).end();
it != itEnd; ++it)
{
sendMessage("RCPT TO: <" + (*it)->getAddress() + ">");
2011-08-30 18:59:16 +00:00
waitForResponse();
if (responseCode != 250) return false;
}
// Send DATA command
sendMessage("DATA");
waitForResponse();
if (responseCode != 354) return false;
sendMessage(email.toString());
// Send \r\n.\r\n to end the mail data
2011-08-30 18:59:16 +00:00
sendMessage(".");
waitForResponse();
if (responseCode != 250) return false;
}
catch (ResponseTimeoutException)
{
return false;
}
catch (SendMessageTimeoutException)
{
return false;
}
2011-08-30 18:59:16 +00:00
return true;
}
void SmtpClient::quit()
{
try
{
sendMessage("QUIT");
}
catch(SmtpClient::SendMessageTimeoutException)
{
//Manually close the connection to the smtp server if message "QUIT" wasn't received by the smtp server
if(socket->state() == QAbstractSocket::ConnectedState || socket->state() == QAbstractSocket::ConnectingState || socket->state() == QAbstractSocket::HostLookupState)
socket->disconnectFromHost();
}
2011-08-30 18:59:16 +00:00
}
/* [3] --- */
/* [4] Protected methods */
2015-10-26 15:31:51 +00:00
void SmtpClient::waitForResponse()
2011-08-30 18:59:16 +00:00
{
2012-09-05 16:36:52 +00:00
do {
if (!socket->waitForReadyRead(responseTimeout))
{
emit smtpError(ResponseTimeoutError);
throw ResponseTimeoutException();
}
2011-08-30 18:59:16 +00:00
2012-09-05 16:36:52 +00:00
while (socket->canReadLine()) {
// Save the server's response
responseText = socket->readLine();
2011-08-30 18:59:16 +00:00
2012-09-05 16:36:52 +00:00
// Extract the respose code from the server's responce (first 3 digits)
responseCode = responseText.left(3).toInt();
2011-08-30 18:59:16 +00:00
2012-09-05 16:36:52 +00:00
if (responseCode / 100 == 4)
emit smtpError(ServerError);
if (responseCode / 100 == 5)
emit smtpError(ClientError);
2011-08-30 18:59:16 +00:00
2012-09-05 16:36:52 +00:00
if (responseText[3] == ' ') { return; }
}
} while (true);
2011-08-30 18:59:16 +00:00
}
2015-10-26 15:31:51 +00:00
void SmtpClient::sendMessage(const QString &text)
2011-08-30 18:59:16 +00:00
{
socket->write(text.toUtf8() + "\r\n");
if (! socket->waitForBytesWritten(sendMessageTimeout))
{
emit smtpError(SendDataTimeoutError);
throw SendMessageTimeoutException();
}
2011-08-30 18:59:16 +00:00
}
/* [4] --- */
/* [5] Slots for the socket's signals */
2015-10-26 15:31:51 +00:00
void SmtpClient::socketStateChanged(QAbstractSocket::SocketState /*state*/)
2011-08-30 18:59:16 +00:00
{
}
2015-10-26 15:31:51 +00:00
void SmtpClient::socketError(QAbstractSocket::SocketError /*socketError*/)
2011-08-30 18:59:16 +00:00
{
}
void SmtpClient::socketReadyRead()
{
}
/* [5] --- */