SMTP Auth Mail senden....

Code-Schnippsel, oder Tipps und Tricks, die einem beim Programmieren mit Qt helfen können.
Antworten
patrik08
Beiträge: 746
Registriert: 27. Februar 2006 10:48
Wohnort: DE Freiburg

SMTP Auth Mail senden....

Beitrag von patrik08 »

Fuer gewohnlich kann leider nur Mac & Linux mail senden Ueber den localhost

Damit alle OS mail senden koennen braucht es ein Smtp Autorisation mail postfach account... nicht hotmail oder gmx free mail account...
Sondern eben ein richtigen Provider der so was zur verfugung gibt ... damit mann mit einem Notebook zum beispiel von ueberall mail senden kann..

im ***.pro file

QT += network
## aktivieren...

in der funktion TimeStampMail() die richtige zeit setzen +0100 je nach ort des senden ...


smtp.h file

Code: Alles auswählen

#ifndef SMTP_H
#define SMTP_H

#include <QTcpSocket>
#include <QString>
#include <QTextStream>
#include <QDebug>
#include <QMessageBox>
#include <QAbstractSocket>
#include <QDateTime>
#include <QDate>
/*
      USAGE!
      Smtp *newMail  = new Smtp("from@address.com","to@address.com"," Your Subject","My body text");
      class emit ErrorCloseAll() / SuccessQuit()   or get QStringList ErrorMSG; to read error and data....
      
*/

class Smtp : public QObject
{
    Q_OBJECT
    
public:
    Smtp( const QString &from, const QString &to,
    const QString &subject, const QString &body );
    ~Smtp();
    int linesend;
    QStringList ErrorMSG; 
 
signals:
    void status( const QString &);
    void ConnectorSuccess();
    void SendLine();
    void ErrorCloseAll();
    void SuccessQuit();

private slots:
    void disconnected();
    void connected();
    void ReadLiner();
    void PutSendLine();
private:
    QString smtpusername;
    QString smtppass;
    QString message;
    QString output;
    QString RemoteServerName;
    QString mailstatus;
    QTextStream *t;
    QTcpSocket *smtpsocket;
    QString from;
    QString rcpt;
    QString response;
    QString SendLineAndGrab(QString senddata);
    int Timeout;
    QString encodeBase64( QString xml );
    QString decodeBase64( QString xml );
    QString TimeStampMail();
    
 
};

#endif


smtp.cpp file

Code: Alles auswählen


#include "smtp.h"
 
Smtp::Smtp( const QString &from, const QString &to, const QString &subject, const QString &body )
{
    
    const QString smtphost = "server.com";
    smtpusername ="user";
    smtppass = "pass";
    
    int waittime = 5 * 1000;
    this->from = from;
    rcpt = to;
    ErrorMSG.clear();
    
    Timeout = waittime;
    linesend = 0;
    
    
    
    message = TimeStampMail()+"\n";
    message.append("User-Agent: Mozilla Thunderbird 1.0.6 (Macintosh/20050716)\n");
    message.append("X-Accept-Language: en-us, en\n");
    message.append("MIME-Version: 1.0\n");
    message.append("To: " + to + "\n");
    message.append("From: "+from+" <" + from + ">\n");
    message.append("Subject: " + TimeStampMail() + "\n");
    message.append("Content-Type: text/plain; charset=UTF8;\n");
    message.append("Content-transfer-encoding: 7BIT\n\n\n\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" ) );
    
    qDebug() << "### Launch mail compose....  "  << from << to << subject << body;
    qDebug() << "### Config server smtp connect to......  "  << smtphost;
    smtpsocket = new QTcpSocket(this);
    connect( this, SIGNAL(ConnectorSuccess()), this ,SLOT(ReadLiner())); 
    connect( this, SIGNAL(SendLine()), this ,SLOT(PutSendLine()));      
    smtpsocket->connectToHost(smtphost,25);
    if (smtpsocket->waitForConnected(Timeout)) {
    qDebug() <<"### connected on  " << smtphost; 
         if (smtpsocket->waitForReadyRead(Timeout)) {
          qDebug() <<"### emit from waitForReadyRead connect go can read";
          emit ConnectorSuccess();
          } 
    } else {
        emit ErrorCloseAll();
    }
   
}

void Smtp::ReadLiner()
{
        qDebug() << "### socketType = " << smtpsocket->socketType();
        qDebug() << "### ReadLiner is start by textstream ";
        t = new QTextStream( smtpsocket );
        int loops = 0;
        while (!t->atEnd()) {
        loops++;
        response = t->readLine();
        qDebug() << loops << " in line  " << response;
        }
        if (response.size() > 0) {
        RemoteServerName = response;
        mailstatus = response.left(3);
        qDebug() << "###Status=" << mailstatus;
                if (mailstatus == "220") {
                response="";
                linesend = 1;
                emit SendLine();
                }
        } else {
           emit ErrorCloseAll(); 
        }
}

Smtp::~Smtp()

{
    delete t;
    delete smtpsocket;
}

/* LINE SENDER  */
void Smtp::PutSendLine()
{
    int current = linesend;
    qDebug() <<"### Go and Send line " << linesend;
    switch(current) {
      case 1:
          response = SendLineAndGrab("ehlo localhost");
           if (response.size() > 0) {
               ErrorMSG.append(response);
               qDebug() << "1---- " << response;
                linesend = 2;
                emit SendLine();
           } else {
                qDebug() << "Connection loost";
                emit ErrorCloseAll();
           }
          response ="";
      break;
      case 2:
          response = SendLineAndGrab("AUTH LOGIN");
           if (response.size() > 0) {
           ErrorMSG.append(response);
                qDebug() << "2---- " << response;
                linesend = 3;
                emit SendLine();
           } else {
                qDebug() << "Connection loost";
                emit ErrorCloseAll();
           }
          response ="";
      break;
      case 3:
          response = SendLineAndGrab(encodeBase64(smtpusername));   /* username send */
           if (response.size() > 0) {
           ErrorMSG.append(response);
                qDebug() << "3---- " << response;
                linesend = 4;
                emit SendLine();
           } else {
                qDebug() << "Connection loost";
                emit ErrorCloseAll();
           }
          response ="";
      break;
      case 4:
          response = SendLineAndGrab(encodeBase64(smtppass));     /* pass send */
           qDebug() << "4---- " << response;
           if (response.size() > 0) {
           ErrorMSG.append(response);
                if (response.contains("ok", Qt::CaseInsensitive)) {
                   linesend = 5;
                   emit SendLine();
                } else {
                   qDebug() << "Connection loost";
                   emit ErrorCloseAll();
                }
           } else {
                qDebug() << "Connection loost";
           }
          response ="";
      break;
      case 5:
          response = SendLineAndGrab("MAIL FROM: "+from);
           qDebug() << "5---- " << response;
           if (response.size() > 0) {
                linesend = 6;
                emit SendLine();               
           } else {
                qDebug() << "Connection loost";
                emit ErrorCloseAll();
           }
          
      break;
      case 6:
          response = SendLineAndGrab("RCPT TO: "+rcpt);
           qDebug() << "6---- " << response;
           if (response.size() > 0) {
                ErrorMSG.append(response);
                response ="";
                response = SendLineAndGrab("DATA");
                         if (!response.contains("not", Qt::CaseInsensitive)) {
                         ErrorMSG.append(response);
                         response ="";             
                         linesend = 7;
                         emit SendLine();                      
                         } else {
                             qDebug() << "Connection loost";
                             emit ErrorCloseAll();
                         }
           } else {
             qDebug() << "Connection loost";
             emit ErrorCloseAll();
           }
          response ="";
      break;
      case 7:
          response = SendLineAndGrab(message+"\r\n.");
           qDebug() << "7---- " << response;
           if (response.size() && response.contains("ok", Qt::CaseInsensitive) ) {
                ErrorMSG.append(response);
                linesend = 8;
                emit SendLine();               
           } else {
                qDebug() << "Connection loost";
                emit ErrorCloseAll();
           }
           response ="";
      break;
      case 8:
          qDebug() << "8---- " << response;
          response = SendLineAndGrab("QUIT");
          ErrorMSG.append(response);
          emit SuccessQuit();
          response ="";
      break;
      default:
      qDebug() << "ERROR!  last loop or false line emit...";
      emit ErrorCloseAll();
      break;
    }   
}

/* SENDER AND RECIVER  */
QString Smtp::SendLineAndGrab(QString senddata)
{
    int current = linesend;
    int loops = 0;
    QString incommingData = "";
    qDebug() << "####Send" << current << "Now => " << senddata;
    *t << senddata << "\r\n";
     t->flush();
          if (smtpsocket->waitForReadyRead(Timeout)) {
                    while (!t->atEnd()) {
                    loops++;
                    QString opera = t->readLine()+"\n";
                    incommingData = opera + incommingData;
                    qDebug() << loops << "|#" << opera << "#|";
                    }
          } 
return incommingData;
}
 
void Smtp::disconnected()
{
    qDebug() <<"disconneted";
    qDebug() << "error "  << smtpsocket->errorString();
}
void Smtp::connected()
{
    output.append("connected");
    qDebug() << "Connected ";
}

QString Smtp::encodeBase64( QString xml )
{
    QByteArray text;
    text.append(xml);
    return text.toBase64();
}

QString Smtp::decodeBase64( QString xml )
{
    QByteArray xcode("");;
    xcode.append(xml);
    QByteArray precode(QByteArray::fromBase64(xcode));
    QString notetxt = precode.data();
    return notetxt;
}

QString Smtp::TimeStampMail()
{
    /* Date: Mon, 08 May 2006 17:57:52 +0200 */
    /* Date: Sun, 28 May 2006 06:32:25 -0420 */
    QDateTime dt = QDateTime::currentDateTime();
    QDate timecute;
    QString day_en = timecute.shortDayName(timecute.day());
    QString month_en = timecute.shortMonthName (timecute.month());
    QString last = dt.toString("yyyy hh:mm:ss"); 
    QString maildate = QString( "Date: %1, %2 %3 %4 +0200" ).arg( day_en , QString::number(timecute.day()), month_en ,   last );
return maildate;
}


/*
220 remote.com ESMTP
ehlo localhost
250-remote.com
250-STARTTLS
250-PIPELINING
250-8BITMIME
250-SIZE 0
250 AUTH LOGIN PLAIN CRAM-MD5
http://www.projektfarm.com/en/support/howto/postfix_smtp_auth_tls.html
*/




toem
Beiträge: 124
Registriert: 17. März 2009 14:01

Beitrag von toem »

Und wie bringe ich dieses Teil zum rennen?

Ich versteh den Code irgendwie total nicht. Ne Verbindung zum Server wird zwar aufgebaut, aber wie sende ich nun?
Zuletzt geändert von toem am 29. Oktober 2009 11:17, insgesamt 1-mal geändert.
Volker
Beiträge: 343
Registriert: 30. Juni 2005 05:27

Re: SMTP Auth Mail senden....

Beitrag von Volker »

patrik08 hat geschrieben: nicht hotmail oder gmx free mail account...
Versteh ich nicht? Warum sollte ich nicht über mail.gmx.net per SMTP versenden können?

Was ich auch nicht ganz verstehe, warum machst Du alles über signal und slots? So lange du nicht beides per Qt::QueuedConnection verbindest, is es doch nur eine umständlichere Variante eines einfachen Funktionsaufrufs oder?

Und wo ich auch bissle irritiert bin is beim Header. Du schreibst ja:
Content-Type: text/plain; charset=UTF8
und
Content-transfer-encoding: 7BIT
aber schickst dann einfach den Body Text so wie er rein kommt übern Socket. Passt das zusammen?

Nicht falsch verstehen, ich find's gut, wenn jamand solche Snippets veröffentlicht, wollte nur nachfragen.
Bitte seid so nett und ändert den Titel von Beiträgen die gelöst wurden, auf [gelöst] Beitragstitel
Antworten