I am new to c++ and tring to send a mail using gmail smtp. I have done this in python but I am unable to do it in c++. I think I need to add startTLS() but it seems to be not defined. Please help me, I have tried my best. Searched the internet also could not find any thing.
#include <cstdlib>
#include <iostream>
#include <Poco/Net/SMTPClientSession.h>
#include <Poco/Net/MailMessage.h>
#include <string>
using namespace Poco::Net;
using namespace std;
int main(int argc, char** argv)
{
std::string Username = "farhantestingsmtp#gmail.com";
std::string Password = "cpguxktxoyibiybd";
std::string Receiver = "jattfarhan10#gmail.com";
std::string Name = "Jatt Farhan";
std::string Subject = "Hello!";
std::string Content = "TEXT OF THE EMAIL";
try
{
MailMessage msg;
msg.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, Receiver, Name));
msg.setSender(Username);
msg.setSubject(Subject);
msg.setContent(Content);
SMTPClientSession smtp("smtp.gmail.com", 487);
smtp.open();
cout << "Before Login";
smtp.login(SMTPClientSession::AUTH_LOGIN, Username, Password);
cout << "After Login";
smtp.sendMessage(msg);
smtp.close();
std::cerr << "Sent mail successfully!" << std::endl;
}
catch (std::exception& e)
{
std::cerr << "Failed to send mail: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
I have added my mail username and password, as it for testing. Thanks in advance.
I tried to add startTLS and could not do it as The SecureSMTPClientSession was not defined in my VS environment. I also searched the internet, but could not fix it.
Related
I learn how to use C++ for network stuff, so first thing i tried is to send email with Poco C++ library. I used vcpkg to install poco with openssl, and it compiles fine
I take code like example from that question:
Sending HTML code in a mail using Poco library
Where dude could send text, but couldn't send file, so i thought that i could reproduce his result quickly, and send some text too, but it doesn't works at all
It Creates Secure SMTP session, but when i try to open it, program just stops
There's my code:
#include <Poco\Net\AcceptCertificateHandler.h>
#include <Poco\Net\FilePartSource.h>
#include <Poco\Net\InvalidCertificateHandler.h>
#include <Poco\Net\MailMessage.h>
#include <Poco\Net\NetException.h>
#include <Poco\Net\SecureSMTPClientSession.h>
#include <Poco\Net\SSLManager.h>
#include <iostream>
namespace pn = Poco::Net;
struct info
{
std::string sender;
std::string recipient;
std::string password;
std::string host;
int port;
};
void MailSender(info a)
{
Poco::Net::MailMessage mailMessage;
mailMessage.addRecipient(Poco::Net::MailRecipient(Poco::Net::MailRecipient::PRIMARY_RECIPIENT, a.recipient, "username"));
mailMessage.setSubject("test");
mailMessage.setSender(a.sender);
mailMessage.setContent("Oh yeah!\r\n");
Poco::Net::SecureSMTPClientSession session(a.host, a.port);
std::cout << "> Session created\n";
session.open();
std::cout << "> Session opened\n";
Poco::Net::initializeSSL();
std::cout << "> SSL initialized\n";
Poco::SharedPtr<Poco::Net::InvalidCertificateHandler> ptrHandler = new Poco::Net::AcceptCertificateHandler(false);
Poco::Net::Context::Ptr ptrContext = new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", Poco::Net::Context::VERIFY_RELAXED, 9, "ALL:!ADH:!LOW:!EXP:!MD5:#STRENGTH");
Poco::Net::SSLManager::instance().initializeClient(NULL, ptrHandler, ptrContext);
std::cout << "> Client initialized\n";
try
{
session.login();
std::cout << "> 1 login completed\n";
if (session.startTLS(ptrContext))
{
session.login(Poco::Net::SecureSMTPClientSession::AUTH_LOGIN, a.sender, a.password);
std::cout << "> 2 login\n";
session.sendMessage(mailMessage);
std::cout << "> Message sent\n";
}
session.close();
std::cout << "> Session closed\n";
Poco::Net::uninitializeSSL();
}
catch (Poco::Net::SMTPException& e)
{
std::cout << e.message() << std::endl;
session.close();
Poco::Net::uninitializeSSL();
}
};
int main()
{
info a{ "username#yandex.ru" , "username#yandex.ru" , "application_password" , "smtp.yandex.ru" , 465};
/*
*a.sender = "username#yandex.ru";
*a.recipient = "username#yandex.ru";
*a.password = "application_password";
*a.host = "smtp.yandex.ru";
*a.port = 465;
*/
MailSender(a);
}
Yandex provides instruction for their smtp usage:
https://yandex.ru/support/mail/mail-clients/others.html
Mail server address - smtp.yandex.ru
Port - 465
Security - ssl
I tried mail.ru and yandex.ru with the same result - nothing
I tried version without ssl, still nothing
I tried to turn off my antivirus
i installed openssl#3 using brew and it is installed in classpath:/opt/homebrew/etc/openssl#3
but during installing poco libraries i am keeping the key directory for openssl by using the command-->
cmake .. -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl
what is the use of this command and how to put it correctly.
but the headers of openssl are not showing inside the /usr/local/include/Poco/Net
because of this, whenever i am compiling the https connection or wss code it is showing HTTPSClientSession.h is not found (fatal error: 'Poco/Net/HTTPSClientSession.h' file not found)
i have done the installation of using this link- https://github.com/pocoproject/poco/tree/3fc3e5f5b8462f7666952b43381383a79b8b5d92
here is the code and please help me with the compiling command and error
fatal error: 'Poco/Net/HTTPSClientSession.h' file not found
#include "Poco/Net/HTTPSClientSession.h"
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
hari-14146:src hari-14146$ vi httpget.cpp
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPCredentials.h"
#include "Poco/StreamCopier.h"
#include "Poco/NullStream.h"
#include "Poco/Path.h"
#include "Poco/URI.h"
#include "Poco/Exception.h"
#include <iostream>
using Poco::Net::HTTPSClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPMessage;
using Poco::StreamCopier;
using Poco::Path;
using Poco::URI;
using Poco::Exception;
using Poco::Net:Context;
bool doRequest(Poco::Net::HTTPSClientSession& session, Poco::Net::HTTPRequest& request, Poco::Net::HTTPResponse& response)
{
session.sendRequest(request);
std::istream& rs = session.receiveResponse(response);
std::cout << response.getStatus() << " " << response.getReason() << std::endl;
if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
{
StreamCopier::copyStream(rs, std::cout);
return true;
}
else
{
Poco::NullOutputStream null;
StreamCopier::copyStream(rs, null);
return false;
}
}
int main(int argc, char** argv)
{
if (argc != 2)
{
Path p(argv[0]);
std::cout << "usage: " << p.getBaseName() << " <uri>" << std::endl;
std::cout << " fetches the resource identified by <uri> and print it to the standard output" << std::endl;
return 1;
}
try
{
URI uri(argv[1]);
std::string path(uri.getPathAndQuery());
if (path.empty()) path = "/";
std::string username;
std::string password;
Poco::Net::HTTPCredentials::extractCredentials(uri, username, password);
Poco::Net::HTTPCredentials credentials(username, password);
//HTTPClientSession session(uri.getHost(), uri.getPort());
const Context::Ptr context(Context::CLIENT_USE, "", "", "", Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:#STRENGTH");
HTTPSClientSession Client(uri.getHost(), uri.getPort(), &context);
HTTPRequest request(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
HTTPResponse response;
if (!doRequest(session, request, response))
{
credentials.authenticate(request, response);
if (!doRequest(session, request, response))
{
std::cerr << "Invalid username or password" << std::endl;
return 1;
}
}
}
catch (Exception& exc)
{
std::cerr << exc.displayText() << std::endl;
return 1;
}
return 0;
how to compile this code and how to give arguments in execution also
how to setup openssl headers in the path /usr/local/include/Poco/Net.
any simple ways to do it and the compiler has to read the header files from above path(/usr/local/include/Poco/Net)
please anyone help me what to do here I am new to c++
I tried this code but I get SMTP Exception, What could I do?
I tried changing the login id and password making sure they are the correct so.
If anyone knows what I can try to make it work I would be very grateful.
// compile with: g++ -Wall -O3 Email.cc -lPocoNet -lPocoFoundation -o Email && ./Email
#include <cstdlib>
#include <iostream>
#include <Poco/Net/SMTPClientSession.h>
#include <Poco/Net/MailMessage.h>
#include <string>
using namespace Poco::Net;
int main(int argc, char **argv)
{
std::string Username = "email_id";
std::string Password = "password";
std::string Receiver = "receiver#gmail.com";
std::string Name = "Charles";
std::string Subject = "Hello!";
std::string Content = "TEXT OF THE EMAIL";
try
{
MailMessage msg;
msg.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, Receiver, Name));
msg.setSender(Username);
msg.setSubject(Subject);
msg.setContent(Content);
SMTPClientSession smtp("smtp.gmail.com");
smtp.login(SMTPClientSession::AUTH_LOGIN, Username, Password);
smtp.sendMessage(msg);
smtp.close();
std::cerr << "Sent mail successfully!" << std::endl;
}
catch (std::exception &e)
{
std::cerr << "Failed to send mail: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Im using libtins library for sniffing.
The given example http_requests.cpp works for HTTP requests.
to capture https packets i tried using
config.set_filter("tcp port 443");
but didn't work
complete code:
#include <string>
#include <iostream>
#include <stdexcept>
#include <boost/regex.hpp>
#include "tins/tcp_ip/stream_follower.h"
#include "tins/sniffer.h"
using std::string;
using std::cout;
using std::cerr;
using std::endl;
using std::exception;
using boost::regex;
using boost::match_results;
using Tins::PDU;
using Tins::Sniffer;
using Tins::SnifferConfiguration;
using Tins::TCPIP::Stream;
using Tins::TCPIP::StreamFollower;
const size_t MAX_PAYLOAD = 3 * 1024;
regex request_regex("([\\w]+) ([^ ]+).+\r\nHost: ([\\d\\w\\.-]+)\r\n");
regex response_regex("HTTP/[^ ]+ ([\\d]+)");
void on_server_data(Stream& stream) {
match_results<Stream::payload_type::const_iterator> client_match;
match_results<Stream::payload_type::const_iterator> server_match;
const Stream::payload_type& client_payload = stream.client_payload();
const Stream::payload_type& server_payload = stream.server_payload();
bool valid = regex_search(server_payload.begin(), server_payload.end(),
server_match, response_regex) &&
regex_search(client_payload.begin(), client_payload.end(),
client_match, request_regex);
if (valid) {
// Extract all fields
string method = string(client_match[1].first, client_match[1].second);
string url = string(client_match[2].first, client_match[2].second);
string host = string(client_match[3].first, client_match[3].second);
string response_code = string(server_match[1].first, server_match[1].second);
// Now print them
cout << method << " http://" << host << url << " -> " << response_code << endl;
// Once we've seen the first request on this stream, ignore it
stream.ignore_client_data();
stream.ignore_server_data();
}
// Just in case the server returns invalid data, stop at 3kb
if (stream.server_payload().size() > MAX_PAYLOAD) {
stream.ignore_server_data();
}
}
void on_client_data(Stream& stream) {
// Don't hold more than 3kb of data from the client's flow
if (stream.client_payload().size() > MAX_PAYLOAD) {
stream.ignore_client_data();
}
}
void on_new_connection(Stream& stream) {
stream.client_data_callback(&on_client_data);
stream.server_data_callback(&on_server_data);
stream.auto_cleanup_payloads(false);
}
int main(int argc, char* argv[]) {
if (argc != 2) {
cout << "Usage: " << argv[0] << " <interface>" << endl;
return 1;
}
try {
SnifferConfiguration config;
config.set_immediate_mode(true);
// Only capture TCP traffic sent from/to port 80
config.set_filter("tcp port 443");
// Construct the sniffer we'll use
Sniffer sniffer(argv[1], config);
cout << "Starting capture on interface " << argv[1] << endl;
// Now construct the stream follower
StreamFollower follower;
follower.new_stream_callback(&on_new_connection);
sniffer.sniff_loop([&](PDU& packet) {
follower.process_packet(packet);
return true;
});
}
catch (exception& ex) {
cerr << "Error: " << ex.what() << endl;
return 1;
}
}
how do i configure it to work for https protocol?
Just changing the port won't actually help.
While it will grab the packets it won't be able to do anything with them as they will be encrypted so none of the regexps will match.
Unless you have access to the private key from the server to decrypt the content then this code will never work.
Another question on a Mysql connection failing:
I'm using the Poco library (1.5.2) and I would like to know why, when I try to open a MySQL connection, I got this message:
Connection attempt failed
Whereas, when I try a connection via console (mysql -u root -p ...), it works.
Maybe I forget an important step in the MySQL configuration ?
Here is my code :
#include <iostream>
#include <string>
#include <Poco/Data/MySQL/MySQLException.h>
#include <Poco/Data/MySQL/Connector.h>
#include <Poco/Data/SessionFactory.h>
using namespace std;
int main()
{
Poco::Data::MySQL::Connector::registerConnector();
try
{
string str = "host=localhost;user=root;password=mypassword;compress=true;auto-reconnect=true";
Poco::Data::Session test(Poco::Data::SessionFactory::instance().create(Poco::Data::MySQL::Connector::KEY, str ));
}
catch (Poco::Data::MySQL::ConnectionException& e)
{
cout << e.what() << endl;
return -1;
}
catch(Poco::Data::MySQL::StatementException& e)
{
cout << e.what() << endl;
return -1;
}
return 0;
}
Thank you !!
ok the problem was the "localhost" value for "host" doesn't work on my linux (I don't know why). For fixing the bug, I had to change my string to:
string str = "host=127.0.0.1;user=root;password=mypassword;compress=true;auto-reconnect=true";