Page 1 of 2 12 LastLast
Results 1 to 20 of 35

Thread: Sending email using Qt.

  1. #1
    Join Date
    Feb 2006
    Posts
    47
    Thanks
    4
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Lightbulb Sending email using Qt.

    Is there a simple way to send email using Qt?
    I see that it can be done by using ActiveQt to control Outlook. I am not interested in doing this. Is there another way?

  2. #2
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    5,372
    Thanks
    28
    Thanked 976 Times in 912 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Sending email using Qt.


  3. The following user says thank you to jacek for this useful post:

    johnny_sparx (15th May 2006)

  4. #3
    Join Date
    Mar 2006
    Posts
    2
    Thanks
    2
    Thanked 6 Times in 2 Posts
    Qt products
    Qt4
    Platforms
    Windows

    Default Re: Sending email using Qt.

    Quote Originally Posted by johnny_sparx
    Is there a simple way to send email using Qt?
    I see that it can be done by using ActiveQt to control Outlook. I am not interested in doing this. Is there another way?
    Depending on the version of QT, the 3.x series had a smtp mail example in the "networking" examples.

    The modified structure for QT 4.x is below:

    smtp.h

    Qt Code:
    1. /****************************************************************************
    2. ** $Id: qt/smtp.h 3.3.6 edited Aug 31 2005 $
    3. **
    4. ** Copyright (C) 1992-2005 Trolltech AS. All rights reserved.
    5. **
    6. ** This file is part of an example program for Qt. This example
    7. ** program may be used, distributed and modified without limitation.
    8. **
    9. *****************************************************************************/
    10.  
    11. #ifndef SMTP_H
    12. #define SMTP_H
    13.  
    14. #include <QTcpSocket>
    15. #include <QString>
    16. #include <QTextStream>
    17. #include <QDebug>
    18. #include <QMessageBox>
    19.  
    20. class Smtp : public QObject
    21. {
    22. Q_OBJECT
    23.  
    24.  
    25. public:
    26. Smtp( const QString &from, const QString &to,
    27. const QString &subject, const QString &body );
    28. ~Smtp();
    29.  
    30. signals:
    31. void status( const QString &);
    32.  
    33. private slots:
    34. void stateChanged(QTcpSocket::SocketState socketState);
    35. void errorReceived(QTcpSocket::SocketError socketError);
    36. void disconnected();
    37. void connected();
    38. void readyRead();
    39.  
    40. private:
    41. QString message;
    42. QTcpSocket *socket;
    43. QString from;
    44. QString rcpt;
    45. QString response;
    46. enum states{Rcpt,Mail,Data,Init,Body,Quit,Close};
    47. int state;
    48.  
    49. };
    50. #endif
    To copy to clipboard, switch view to plain text mode 

    smtp.cpp
    Qt Code:
    1. #include "smtp.h"
    2.  
    3. Smtp::Smtp( const QString &from, const QString &to, const QString &subject, const QString &body )
    4. {
    5. socket = new QTcpSocket( this );
    6.  
    7. connect( socket, SIGNAL( readyRead() ), this, SLOT( readyRead() ) );
    8. connect( socket, SIGNAL( connected() ), this, SLOT( connected() ) );
    9. connect( socket, SIGNAL(error(SocketError)), this,
    10. SLOT(errorReceived(SocketError)));
    11. connect( socket, SIGNAL(stateChanged( SocketState)), this,
    12. SLOT(stateChanged(SocketState)));
    13. connect(socket, SIGNAL(disconnectedFromHost()), this,
    14. SLOT(disconnected()));;
    15.  
    16. message = "To: " + to + "\n";
    17. message.append("From: " + from + "\n");
    18. message.append("Subject: " + subject + "\n");
    19. message.append(body);
    20. message.replace( QString::fromLatin1( "\n" ), QString::fromLatin1( "\r\n" ) );
    21. message.replace( QString::fromLatin1( "\r\n.\r\n" ),
    22. QString::fromLatin1( "\r\n..\r\n" ) );
    23. this->from = from;
    24. rcpt = to;
    25. state = Init;
    26. socket->connectToHost( "smtp.yourserver.com", 25);
    27. if(socket->waitForConnected ( 30000 )) {qDebug("connected"); }
    28.  
    29. t = new QTextStream( socket );
    30. }
    31. Smtp::~Smtp()
    32. {
    33. delete t;
    34. delete socket;
    35. }
    36. void Smtp::stateChanged(QTcpSocket::SocketState socketState)
    37. {
    38.  
    39. qDebug() <<"stateChanged " << socketState;
    40. }
    41.  
    42. void Smtp::errorReceived(QTcpSocket::SocketError socketError)
    43. {
    44. qDebug() << "error " <<socketError;
    45. }
    46.  
    47. void Smtp::disconnected()
    48. {
    49.  
    50. qDebug() <<"disconneted";
    51. qDebug() << "error " << socket->errorString();
    52. }
    53.  
    54. void Smtp::connected()
    55. {
    56. output->append("connected");
    57. qDebug() << "Connected ";
    58. }
    59.  
    60. void Smtp::readyRead()
    61. {
    62.  
    63. qDebug() <<"readyRead";
    64. // SMTP is line-oriented
    65.  
    66. QString responseLine;
    67. do
    68. {
    69. responseLine = socket->readLine();
    70. response += responseLine;
    71. }
    72. while ( socket->canReadLine() && responseLine[3] != ' ' );
    73.  
    74. responseLine.truncate( 3 );
    75.  
    76.  
    77. if ( state == Init && responseLine[0] == '2' )
    78. {
    79. // banner was okay, let's go on
    80.  
    81. *t << "HELO there\r\n";
    82. t->flush();
    83.  
    84. state = Mail;
    85. }
    86. else if ( state == Mail && responseLine[0] == '2' )
    87. {
    88. // HELO response was okay (well, it has to be)
    89.  
    90. *t << "MAIL FROM: " << from << "\r\n";
    91. t->flush();
    92. state = Rcpt;
    93. }
    94. else if ( state == Rcpt && responseLine[0] == '2' )
    95. {
    96.  
    97. *t << "RCPT TO: " << rcpt << "\r\n"; //r
    98. t->flush();
    99. state = Data;
    100. }
    101. else if ( state == Data && responseLine[0] == '2' )
    102. {
    103.  
    104. *t << "DATA\r\n";
    105. t->flush();
    106. state = Body;
    107. }
    108. else if ( state == Body && responseLine[0] == '3' )
    109. {
    110.  
    111. *t << message << "\r\n.\r\n";
    112. t->flush();
    113. state = Quit;
    114. }
    115. else if ( state == Quit && responseLine[0] == '2' )
    116. {
    117.  
    118. *t << "QUIT\r\n";
    119. t->flush();
    120. // here, we just close.
    121. state = Close;
    122. emit status( tr( "Message sent" ) );
    123. }
    124. else if ( state == Close )
    125. {
    126. deleteLater();
    127. return;
    128. }
    129. else
    130. {
    131. // something broke.
    132. QMessageBox::warning( 0, tr( "Qt Mail Example" ), tr( "Unexpected reply from SMTP server:\n\n" ) + response );
    133. state = Close;
    134. }
    135. response = "";
    136. }
    To copy to clipboard, switch view to plain text mode 

    To send a mail just use:
    Qt Code:
    1. Smtp *newMail = new Smtp("from@address.com","to@address.com"," Your Subject","My body text");
    2. delete newMail;
    To copy to clipboard, switch view to plain text mode 

    Please note: change the server address in "smtp.cpp" to your local server, most of the time localhost will work.. remote hosts should also work though.

    As well, this may not work right off the bat, i speciallized it to work for my program.. i just hacked it back together for an example. The code is essentially correct, i just usually include the "To: BLAH\n", "From: BLAH\n" and "Subject: BLAH\n" within my message body.. so if there is something wrong it should be in that area.

    Good Luck!

    J

  5. The following 5 users say thank you to nielsenj for this useful post:

    lllturtle (16th August 2011), Persoontje (23rd December 2007), scary hallo (9th January 2014), sunil.thaha (18th December 2006), tablebubble (13th September 2011)

  6. #4
    Join Date
    Jan 2006
    Posts
    14
    Thanked 2 Times in 2 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Sending email using Qt.

    Hi guys,

    I am working on a SMTP client too and I do quite the same things as in the Qt example (btw. I didnt remember there was such an example ).
    The problem is my app won't connect if I don't call waitForConnected()!

    But isnt this method useless if we wand non-blocking sockets?
    Other code examples simply call connectToHost(...) after setting up the right connections.
    If I don't call waitForConnected() the socket status remains on LookingUpHost (or whatever the exact name is)

    Any clue???

  7. #5
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    5,372
    Thanks
    28
    Thanked 976 Times in 912 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Sending email using Qt.

    Quote Originally Posted by blue.death
    If I don't call waitForConnected() the socket status remains on LookingUpHost (or whatever the exact name is)
    Maybe you block the event loop? Do you check socket's status in some kind of a loop?

  8. #6
    Join Date
    Jan 2006
    Posts
    14
    Thanked 2 Times in 2 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Sending email using Qt.

    Quote Originally Posted by jacek
    Maybe you block the event loop? Do you check socket's status in some kind of a loop?
    No, i connected the stateChanged() signal to a slot so I can keep track of the state changes.
    If I don't call waitForConnected the state remains 1 and never changes.
    If i call waitForConnected the connected() signal is emitted and the state changes to 2 and then 3 (connected).

  9. #7
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    5,372
    Thanks
    28
    Thanked 976 Times in 912 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Sending email using Qt.

    Quote Originally Posted by blue.death
    No, i connected the stateChanged() signal to a slot so I can keep track of the state changes.
    Do you have "QT += network" in your .pro file? Do you use threads? Maybe there's a loop that blocks the event loop in some other place?

  10. #8
    Join Date
    Jan 2006
    Posts
    14
    Thanked 2 Times in 2 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Sending email using Qt.

    Quote Originally Posted by jacek
    Do you have "QT += network" in your .pro file? Do you use threads? Maybe there's a loop that blocks the event loop in some other place?
    .pro file is ok, otherwise it wouldnt build at all,
    no threads, thats why i dont want blocking sockets,
    and no event loop blocks

    I'm starting to think it's a problem with my Qt 4.1.3 on windoze.
    I will see if i can post some code tomorrow.. i need some sleep now

  11. #9
    Join Date
    May 2006
    Posts
    788
    Thanks
    49
    Thanked 48 Times in 46 Posts
    Qt products
    Qt4
    Platforms
    MacOS X Unix/X11 Windows

    Default Re: Sending email using Qt.

    I rewrite the troll sample to make SMTP AUTH LOGIN work on qmail & postix tested...

    Important is the mail date ..... the troll sample go unixtime zero 1970....

    Qt Code:
    1. int dateswap(QString form, uint unixtime )
    2. {
    3. QDateTime fromunix;
    4. fromunix.setTime_t(unixtime);
    5. QString numeric = fromunix.toString((const QString)form);
    6. bool ok;
    7. return (int)numeric.toFloat(&ok);
    8. }
    9.  
    10.  
    11. QString TimeStampMail()
    12. {
    13. /* mail rtf Date format! http://www.faqs.org/rfcs/rfc788.html */
    14. uint unixtime = (uint)time( NULL );
    15. QDateTime fromunix;
    16. fromunix.setTime_t(unixtime);
    17. QStringList RTFdays = QStringList() << "giorno_NULL" << "Mon" << "Tue" << "Wed" << "Thu" << "Fri" << "Sat" << "Sun";
    18. QStringList RTFmonth = QStringList() << "mese_NULL" << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun" << "Jul" << "Aug" << "Sep" << "Oct" << "Nov" << "Dec";
    19. QDate timeroad(dateswap("yyyy",unixtime),dateswap("M",unixtime),dateswap("d",unixtime));
    20. /*qDebug() << "### RTFdays " << RTFdays.at(timeroad.dayOfWeek());
    21.   qDebug() << "### RTFmonth " << RTFmonth.at(dateswap("M",unixtime));
    22.   qDebug() << "### yyyy " << dateswap("yyyy",unixtime);
    23.   qDebug() << "### M " << dateswap("M",unixtime);
    24.   qDebug() << "### d " << dateswap("d",unixtime);*/
    25. QStringList rtfd_line;
    26. rtfd_line.clear();
    27. rtfd_line.append("Date: ");
    28. rtfd_line.append(RTFdays.at(timeroad.dayOfWeek()));
    29. rtfd_line.append(", ");
    30. rtfd_line.append(QString::number(dateswap("d",unixtime)));
    31. rtfd_line.append(" ");
    32. rtfd_line.append(RTFmonth.at(dateswap("M",unixtime)));
    33. rtfd_line.append(" ");
    34. rtfd_line.append(QString::number(dateswap("yyyy",unixtime)));
    35. rtfd_line.append(" ");
    36. rtfd_line.append(fromunix.toString("hh:mm:ss"));
    37. rtfd_line.append("");
    38. /*qDebug() << "### mail rtf Date format " << rtfd_line.join("");*/
    39. return QString(rtfd_line.join(""));
    40. }
    To copy to clipboard, switch view to plain text mode 
    Attached Files Attached Files

  12. The following user says thank you to patrik08 for this useful post:

    lllturtle (16th August 2011)

  13. #10
    Join Date
    Mar 2006
    Posts
    2
    Thanks
    2
    Thanked 6 Times in 2 Posts
    Qt products
    Qt4
    Platforms
    Windows

    Default Re: Sending email using Qt.

    Quote Originally Posted by blue.death
    Hi guys,

    I am working on a SMTP client too and I do quite the same things as in the Qt example (btw. I didnt remember there was such an example ).
    The problem is my app won't connect if I don't call waitForConnected()!

    But isnt this method useless if we wand non-blocking sockets?
    Other code examples simply call connectToHost(...) after setting up the right connections.
    If I don't call waitForConnected() the socket status remains on LookingUpHost (or whatever the exact name is)

    Any clue???

    The example was only in the QT 3.x series under networking examples, i just altered it to work in QT 4.x.

    My understanding of the "waitForConnected()" function is that it's simply a delay to allow a handshake to occur, it doesn't actually do anything unless you want to establish a timeout (lets say for a server that's offline) and take the bool return to do error correction.

    Basically it is a delay before completing the socket.

    I removed the "waitForConnected()" from my client and it established a connection immediately, but my mail server is also on the company lan and connects extremely quickly.

    Using the "waitForConnected()" function should have no effect on how you connect unless you choose to implement error correction based on it's return.

    If you don't want to use it then i suggest putting a delay in, something like 10-15 seconds, which is close to a worst case connection delay for most internet applications.

    Of course if you use "waitForConnected(15000)" then it will automatically stop the delay after either 15 seconds (a timeout) or you establish a connection (if it's less than the passed 15 seconds), which would make sense to minimize the time your application is waiting.

    J

  14. The following user says thank you to nielsenj for this useful post:

    marcovictor (8th October 2010)

  15. #11
    Join Date
    Aug 2006
    Location
    Germany
    Posts
    15
    Thanks
    1
    Thanked 3 Times in 1 Post
    Qt products
    Qt4
    Platforms
    Unix/X11

    Default Re: Sending email using Qt.

    Even this Post is old, it was very usefull for me. So a big thank you!!
    But i have to notes for using MS Exchange Server (in my case Version 2000).
    You have to change two things inside the code:
    1. Don´t remove
      Qt Code:
      1. if (smtpsocket->waitForConnected(Timeout))
      To copy to clipboard, switch view to plain text mode 
      or no mails will be send. Instead decrease the timeout, i.e. 500.
    2. In function "PutSendLine()", in step "case 4"
      replace the response "ok" with "Authentication successful" because this is the real responce and it wont work else.

  16. The following 3 users say thank you to pinktroll for this useful post:

    codeslicer (12th February 2008), lllturtle (16th August 2011), mchrk (19th December 2008)

  17. #12

    Default Re: Sending email using Qt.

    Hello,
    I'm newbie and I'd like to understand correctly this code.
    Could you write what is the "output" is it sth. like stdout?:

    Qt Code:
    1. void Smtp::connected()
    2. {
    3. output->append("connected");
    4. qDebug() << "Connected ";
    5. }
    To copy to clipboard, switch view to plain text mode 

    thanks
    Last edited by Ryczypisk; 4th November 2009 at 13:00.

  18. #13
    Join Date
    Feb 2010
    Posts
    68
    Thanks
    8
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Sending email using Qt.

    I used the structure from the post #9, taking into account post #11 (especially the second note). I am successfully connecting to the server and sending it those "lines" until it comes to send line number 7 (function PutSendLine(), case 7) - it's an actual message. After this line:
    Qt Code:
    1. response = SendLineAndGrab(message+"\r\n.");
    To copy to clipboard, switch view to plain text mode 
    I'm receiving such a response from a server:
    "550 5.5.2 Unknown command 'Date: Mon, 8 Mar 2010 15:54:26'
    I have tried to remove the date (by commenting one of the first lines in smtp.cpp), but then I received similar response but this time it was aobut "User-Agent: Mozilla Thunderbird 1.0.6...".

    Why is the server sending such responses? How to make it work?

  19. #14
    Join Date
    Mar 2010
    Posts
    1
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows Symbian S60

    Default Re: Sending email using Qt.

    in step 5
    SendLineAndGrab("MAIL FROM: "+from);
    someserver return:
    501 Bad address syntax
    so this line must chang to:
    SendLineAndGrab("MAIL FROM:<"+from+">");

  20. #15

    Default Re: Sending email using Qt.

    How can we add to this code an option to send attached files?

  21. #16
    Join Date
    Sep 2009
    Location
    UK
    Posts
    2,447
    Thanks
    6
    Thanked 348 Times in 333 Posts
    Qt products
    Qt4
    Platforms
    Windows

    Default Re: Sending email using Qt.

    7-bit encode the attachments using something like Base64 and then attach them to the body of the email as a MIME attachment making sure that the message and each attachment has a different id so that the receiving email client knows how to seperate the parts again.

  22. #17
    Join Date
    Jan 2008
    Location
    Brasil
    Posts
    131
    Thanks
    18
    Thanked 3 Times in 3 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Sending email using Qt.

    See POCO Libraries, its very helpfull
    http://pocoproject.org

  23. #18

    Default Re: Sending email using Qt.

    Quote Originally Posted by fatjuicymole View Post
    7-bit encode the attachments using something like Base64 and then attach them to the body of the email as a MIME attachment making sure that the message and each attachment has a different id so that the receiving email client knows how to seperate the parts again.
    My mayor problem is that i receive an empty file if i do that, i must be doing something wrong

  24. #19
    Join Date
    Mar 2010
    Posts
    3
    Qt products
    Qt4
    Platforms
    Windows

    Default Re: Sending email using Qt.

    OK nielsenj demonstrated a nice axample how to send a mail via SMTP. But I can't find on the internet how to get the mail which is sent by the code of nielsenj.

  25. #20
    Join Date
    Jun 2010
    Posts
    137
    Thanks
    9
    Qt products
    Qt4
    Platforms
    Windows

    Default Re: Sending email using Qt.

    Hi nielsenj,

    I hope you are still active in this forum. I am new to Qt and I have the issue with smtp client. I have fallowed your code and am able to get the connected signal but immediately I am getting disconnected signal. Do you have any Idea why it is happening. I would be grateful to any help.

    Thank you,
    Baluk

Similar Threads

  1. Replies: 9
    Last Post: 23rd August 2012, 00:01
  2. Replies: 7
    Last Post: 5th January 2009, 08:27
  3. Sending Mail through QProcess
    By KaptainKarl in forum Qt Programming
    Replies: 6
    Last Post: 13th August 2008, 21:51
  4. sending encrypted data via mail using smtp
    By vermarajeev in forum General Programming
    Replies: 20
    Last Post: 14th August 2007, 19:47
  5. qt network performance
    By criss in forum Qt Programming
    Replies: 16
    Last Post: 24th July 2006, 09:23

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.