Sending Email to any server in Qt



  • Hi friends,
    I want to send an email to any server(gmail,yahoo,etc) by providing our email id in our Gui itself...It should happen after clicking "send Email" button....I dont want like microsoft outlook....And also it should not go to web browser...Our Email should directly reach to their destination(for eg:xxx@gmail.com)..Please provide me a solution


  • Moderators

    Probably the best is using "Google ":http://lmgtfy.com/?q=qt+email+client or another search engine



  • hi koahnig,
    I have found out in search engine...When i send the mail...After going 57%,it is showing an error message like this..

                                  /*  Unexpected reply from SMTP server:
    

    530 5.7.0 Must issue a STARTTLS command first. qi1sm23508884pac.21 - gsmtp............. */

                                Could any one please sought out my problem please.
    

  • Moderators

    Probably you have to post part of your application and give more information. Otherwise it will be hard for anybody to give a sound feedback.



  • !file:///home/bts-007/Screenshot from 2013-06-19 18:45:45.png!
    This is the image,what i got wen send..


  • Moderators

    The image link you have provided is the link of a local file on your harddisk. Nobody besides you will be able to look at the picture.
    Please check out the "forum help":http://qt-project.org/wiki/ForumHelp#9bd9c32b79efb1b2d5b039e4d48300a9 for assistance in how to post pictures (is number 6).
    However, with any code section of your application, I doubt that anybody may be able to help. You might receive similar responses with a lot of different tools.



  • Thanks mr.koahig,
    Very sorry for the late reply sir..
    !http://imageshack.us/photo/my-images/809/9jye.png/()!
    This is the image,what i got wen i clicks send button..


  • Moderators

    Sorry, but your approach will not work: You can not send mail from arbitrary senders to arbitrary recipients anymore. That was possible for a long time, but nowadays any server still allowing that will be blocked by all others as a spammer.

    You could limit the sender to e.g. a google mail account. You will have a well defined sender then and can do the necessary authentication for the sender. As you see google will require the SSL/TLS encrypted flavor of SMTP and you will need to implement that. You will also need to implement any authentication method google requires.



  • thanks mr.toabias hunger for your response.....Actually i have tried this given below code alone..At starting,it shows some bugs,then i have removed all the bugs by my efforts....I came to understand from your wordings that,it will block that as a spam....could you please tell me what changes i need to do in the codings..below is the code...

    1. /main.cpp/
      @#include "sendmail.h"
      #include <QApplication>

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    SendMail w;
    w.show();
    a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
    return a.exec();
    }
    @

    1. /previewdialog.cpp/

    @#include "previewdialog.h"
    previewDialog::previewDialog(QString message, QWidget *parent)
    : QDialog(parent)
    {
    ui.setupUi(this);
    ui.webView->setHtml(message);

    }

    previewDialog::~previewDialog()
    {

    }
    @

    2.a /previewdialog.h/

    @#ifndef PREVIEWDIALOG_H
    #define PREVIEWDIALOG_H

    #include <QDialog>
    #include <QString>
    #include <QUrl>
    #include <QWebView>
    #include "ui_previewdialog.h"

    class previewDialog : public QDialog
    {
    Q_OBJECT

    public:
    previewDialog(QString message, QWidget *parent = 0);
    ~previewDialog();

    private:
    Ui::previewDialogClass ui;
    };

    #endif // PREVIEWDIALOG_H
    @

    1. /sendmail.cpp/

    @#include "sendmail.h"
    #include "smtp.h"

    SendMail::SendMail(QWidget *parent)
    : QDialog(parent)
    {
    ui.setupUi(this);

    progressDialog = new QProgressDialog ("Sending mail...", "Abort", 0, 7, this);
    connect (progressDialog, SIGNAL(canceled()), this, SLOT(close()));
    progressDialog->hide();
    connect (ui.serverLineEdit, SIGNAL(textChanged(QString)), this, SLOT(enableButtons()));
    connect (ui.fromLineEdit, SIGNAL(textChanged(QString)), this, SLOT(enableButtons()));
    connect (ui.toLineEdit, SIGNAL(textChanged(QString)), this, SLOT(enableButtons()));
    connect (ui.subjectLineEdit, SIGNAL(textChanged(QString)), this, SLOT(enableButtons()));
    connect (ui.messageTextEdit, SIGNAL(textChanged()), this, SLOT(enableButtons()));
    }

    SendMail::~SendMail()
    {

    }

    void SendMail::on_sendButton_clicked()
    {
    QString server = ui.serverLineEdit->text();
    QString from = ui.fromLineEdit->text();
    QString to = ui.toLineEdit->text();
    QString subject = ui.subjectLineEdit->text();
    QString message = ui.messageTextEdit->toPlainText();

    QList<QString> bcc = createList(ui.bccTextEdit->toPlainText());
    Smtp *newMail = new Smtp(server, from,to,bcc,subject,message, true);
    connect (newMail, SIGNAL(status(int)), this, SLOT(updateProgress(int)));
    progressDialog->setValue(0);
    progressDialog->show();
    newMail->send();
    }

    void SendMail::on_previewButton_clicked()
    {
    previewDialog dialog(ui.messageTextEdit->toPlainText());
    dialog.exec();
    }
    void SendMail::enableButtons()
    {
    if ( (ui.serverLineEdit->text() != QString("")) &&
    (ui.fromLineEdit->text() != QString("")) &&
    (ui.toLineEdit->text() != QString("")) &&
    (ui.subjectLineEdit->text() != QString("")) &&
    (ui.messageTextEdit->toPlainText() != QString(""))
    )
    ui.sendButton->setEnabled(true);
    else
    ui.sendButton->setEnabled(false);

    if (ui.messageTextEdit->toPlainText() != QString(""))
    ui.previewButton->setEnabled(true);
    else
    ui.previewButton->setEnabled(false);
    }

    void SendMail::updateProgress(int state)
    {

    qDebug() << state;
    if (state == -1)
    {
    QMessageBox::critical(this, "Error while sending mail", "Error while sending mail.");
    progressDialog->hide();
    }
    progressDialog->setValue(state);
    }

    QList<QString> SendMail::createList(QString str)
    {
    QList<QString> list;
    enum states {seek, read, store,done};
    int state;
    int i = 0;
    QString item = "";
    QChar c;

    //Add an extra ; so it will always include the last email adresst oo
    str.append(';');
    QRegExp regExp("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$", Qt::CaseInsensitive);
    QRegExpValidator validator(regExp, this);
    if(str == "")
    return list;

    state = seek;
    while(state!=done)
    {
    c = str[i];
    if (state==seek)
    {
    if(c == ' ' || c == ';')
    {
    //Keep seeking
    state=seek;
    }
    else
    {
    //Found item
    state=read;
    }
    }
    if (state==read)
    {
    //Check for end of this item
    if(c == ';')
    {
    //End so store it
    state=store;
    }
    else
    {
    //Read
    item += c;
    }
    }
    if (state==store)
    {
    //Store item
    //Strip /n
    item.replace( QString::fromLatin1( "\n" ), QString::fromLatin1( "" ) );
    //Validate
    int pos = 0;
    if(validator.validate(item, pos) != QValidator::Acceptable)
    {
    bool ok;
    item = QInputDialog::getText(this, tr("Wrong email-adress"),
    tr("The email adress you provided is wrong. Please enter a new one:"),
    QLineEdit::Normal,
    item,
    &ok);
    if (ok)
    {
    //Store again
    state=store;
    continue;
    }
    }
    else
    {
    list.append(item);
    }
    item.clear();
    state=seek;
    }
    //Increase I, check if we're done
    if (i >= str.length())
    state=done;
    else
    i++;

    }

    return list;
    }
    @

    3.a * /sendmail.h/*

    @#ifndef SENDMAIL_H
    #define SENDMAIL_H

    #include <QDialog>
    #include <QProgressDialog>
    #include <QMessageBox>
    #include <QDebug>
    #include <QList>
    #include <QChar>
    #include <QRegExp>
    #include <QRegExpValidator>
    #include <QInputDialog>
    #include "previewdialog.h"
    #include "ui_sendmail.h"

    class SendMail : public QDialog
    {
    Q_OBJECT

    public:
    SendMail(QWidget *parent = 0);
    ~SendMail();

    private:
    Ui::SendMailClass ui;
    QProgressDialog* progressDialog;

    QList<QString> createList(QString str);
    

    private slots:
    void on_sendButton_clicked();
    void on_previewButton_clicked();
    void enableButtons();
    void updateProgress(int state);
    };

    #endif // SENDMAIL_H
    @



  • Remaining code is here,

    1. /smtp.cpp/

    @#include "smtp.h"
    Smtp::Smtp( const QString &server, const QString &from, const QString &to, const QList<QString> &bcc, const QString &subject, const QString &body, const bool html )
    {
    socket = new QTcpSocket( this );

    connect( socket, SIGNAL( readyRead() ), this, SLOT( readyRead() ) );
    connect( socket, SIGNAL( connected() ), this, SLOT( connected() ) );
    connect( socket, SIGNAL(error(QAbstractSocket::SocketError)), this, 
    

    SLOT(errorReceived(QAbstractSocket::SocketError)));
    connect( socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this,
    SLOT(stateChanged(QAbstractSocket::SocketState)));
    connect(socket, SIGNAL(disconnected()), this,
    SLOT(disconnected()));;

    //Generate date
    QTime myTime = QDateTime::currentDateTime().toUTC().time();
    QLocale myLocal = QLocale(QLocale::C);
    QString date = myLocal.toString(QDate::currentDate(), "ddd, dd MMM yyyy ");
    date += myLocal.toString(myTime, "hh:mm:ss");
    date += " +0000 (UTC)";

    message = "To: " + to + "\n";
    message.append("From: " + from + "\n");
    message.append("Subject: " + subject + "\n");
    message.append("Date: " + date + "\n");

    if(html)
    {
    message.append("MIME-Version: 1.0 \n");
    message.append("Content-Type: text/html; charset="iso-8859-1"; format=flowed \n");
    }
    message.append(body);
    message.replace( QString::fromLatin1( "\n" ), QString::fromLatin1( "\r\n" ) );
    message.replace( QString::fromLatin1( "\r\n.\r\n" ),
    QString::fromLatin1( "\r\n..\r\n" ) );
    this->from = from;

    //Add to adress
    rcpt = bcc;
    rcpt.insert(0, to); 
    rcptIndex = 0;
    
    this->server = server;
    

    }

    void Smtp::send()
    {
    state = Init;
    emit status( 1 ); //Connecting
    socket->connectToHost( server, 25);
    if(socket->waitForConnected ( 100000 )) {qDebug("constructor"); }
    t = new QTextStream( socket );
    emit status( 2 ); //Connected
    }
    Smtp::~Smtp()
    {
    delete t;
    delete socket;
    }
    void Smtp::stateChanged(QAbstractSocket::SocketState socketState)
    {

    qDebug() <<"stateChanged " << socketState;
    

    }

    void Smtp::errorReceived(QAbstractSocket::SocketError socketError)
    {
    qDebug() << "error " <<socketError;
    }

    void Smtp::disconnected()
    {

    qDebug() <<"disconneted";
    qDebug() << "error "  << socket->errorString();
    

    }

    void Smtp::connected()
    {
    qDebug() << "Connected ";
    }

    void Smtp::readyRead()
    {

     qDebug() <<"readyRead";
    // SMTP is line-oriented
    
    QString responseLine;
    do
    {
        responseLine = socket->readLine();
        response += responseLine;
    }
    while ( socket->canReadLine() && responseLine[3] != ' ' );
    

    responseLine.truncate( 3 );

    if ( state == Init && responseLine[0] == '2' )
    {
        // banner was okay, let's go on
    

    *t << "HELO there\r\n";
    t->flush();

        state = Mail;
        emit status( 3 ); //Sending
    }
    else if ( state == Mail && responseLine[0] == '2' )
    {
        // HELO response was okay (well, it has to be)
    
        *t << "MAIL FROM: " << from << "\r\n";
    

    t->flush();
    state = Rcpt;
    emit status( 4 ); //Sending
    }
    else if ( state == Rcpt && responseLine[0] == '2' )
    {
    QString adress = rcpt[rcptIndex];
    *t << "RCPT TO: " << rcpt[rcptIndex] << "\r\n"; //r
    rcptIndex++;
    t->flush();
    emit status( 5 ); //Sending
    if (rcptIndex >= rcpt.size())
    state = Data;
    }
    else if ( state == Data && responseLine[0] == '2' )
    {

        *t << "DATA\r\n";
    

    t->flush();
    state = Body;
    emit status( 6 ); //Sending
    }
    else if ( state == Body && responseLine[0] == '3' )
    {

        *t << message << "\r\n.\r\n";
    

    t->flush();
    state = Quit;
    }
    else if ( state == Quit && responseLine[0] == '2' )
    {

        *t << "QUIT\r\n";
    

    t->flush();
    // here, we just close.
    state = Close;
    emit status( 7 ); //Sending
    }
    else if ( state == Close )
    {
    deleteLater();
    return;
    }
    else
    {
    // something broke.
    QMessageBox::warning( 0, tr( "Qt Mail Example" ), tr( "Unexpected reply from SMTP server:\n\n" ) + response );
    emit status(-1);
    state = Close;
    }
    response = "";
    }
    @

    4.a.* /smtp.h/*

    @#ifndef SMTP_H
    #define SMTP_H

    #include <QApplication>
    #include <QMessageBox>
    #include <QtDebug>
    #include <QString>
    #include <QObject>
    #include <QTcpSocket>
    #include <QTextStream>
    #include <QDate>
    #include <QTime>
    #include <QDateTime>
    #include <QLocale>
    #include <QList>

    class Smtp : public QObject
    {
    Q_OBJECT

    public:
    Smtp( const QString &server, const QString &from, const QString &to, const QList<QString> &bcc,
    const QString &subject, const QString &body, const bool html = false);
    ~Smtp();

    void send();
    

    signals:
    void status( const int);

    private slots:

    void stateChanged(QAbstractSocket::SocketState socketState);
    void errorReceived(QAbstractSocket::SocketError socketError);
    void disconnected();
    void connected();
    void readyRead();
    private:
    QString message;
    QTextStream *t;
    QTcpSocket socket;
    QString server;
    QString from;
    QList<QString> rcpt;
    int rcptIndex;
    QString response;
    enum states{Rcpt,Mail,Data,Init,Body,Quit,Close};
    int state;
    };
    #endif /
    SMTP_H */
    @


  • Moderators

    Your code would most likely have worked fine in the late 1980s... But with all the efforts to limit spam mails you will have to adjust your code a lot.

    What I meant by my comment on spam is this:

    Assuming you have a smtp-server which is registered as being responsible for "foo.com" (let's call it "mail.foo.com") . Now you use "mail.foo.com" to send mails from "bar@hotmail.com" to "foobar@gmail.com".

    First "mail.foo.com" will not allow you to send mails that do not belong to his area. So "mail.foo.com" will reject sending mails from "bar@hotmail.com".

    So let's try to use "mail.foo.com" to send mail from "bar@foo.com"...

    "mail.foo.com" will require the user "bar" to authenticate. There are several approaches to do that. You will need to implement those to use any real-world mailservers. There are quite a few in use, ranging from "pop-before-smtp" to SASL.

    Let's assume you find a nice, 1980-style mailserver somewhere that will happily relay mails for anybody and not require any authentication. Let's call it "mail.idiotadmin.com". You can use "mail.idiotadmin.com" in your application. It will accept your sender "foo@hotmail.com" and recipient "bar@gmail.com" and your code will work fine. But still: "bar@gmail.com" will never ever see the mail.

    Your problem is that the mailserver handling "gmail.com" will just drop those mails: "mail.idiotadmin.com" is going to be blacklisted since hundreds of spammers willl have tried used it to send their spam. Even if you are lucky and the server is not blacklisted the mails will be dropped, as gmail.com will not accept mails claiming to originate from "hotmail.com" from a server handling "idiotadmin.com".

    Finally many mailservers nowadays require encrypted connections. Google mail is one such service AFAIK (looks like google wants to block everybody but the NSA from accessing your mails;). So you will need to implement SSL/TLS support (which is initiated by the STARTTLS command you are seeing).



  • Thanks sir,
    I came to understand your thoughts......TLS means Transport Layer Security protocol,Ok now wat i need to do....How can we send the mail by inserting that STARTTLS command.....could you please explain it in technical way(in coding style)..Please favour me an example..thanks in advance


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.