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;
}
Related
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.
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 am currently trying to establish a stream connection between my AWSClient and a Lex Bot.
I am getting the following error:
aws-sdk-cpp/aws-cpp-sdk-core/source/auth/signer-provider/DefaultAuthSignerProvider.cpp:48: virtual std::shared_ptr<Aws::Client::AWSAuthSigner> Aws::Auth::DefaultAuthSignerProvider::GetSigner(const String&) const: Assertion `false' failed.
Aborted (core dumped)
when the code run through the following line:
lexClient->StartConversationAsync(LexRequest, OnStreamReady, OnResponseCallback, nullptr);
starting.WaitOne();
the entire .cpp follows:
#include <aws/core/Aws.h>
#include <aws/core/client/AsyncCallerContext.h>
#include <aws/core/utils/Outcome.h>
#include <aws/core/auth/AWSCredentialsProvider.h>
#include <aws/lexv2-runtime/LexRuntimeV2Client.h>
#include <aws/lexv2-runtime/model/AudioInputEvent.h>
#include <aws/lexv2-runtime/model/RecognizeUtteranceRequest.h>
#include <aws/lexv2-runtime/model/RecognizeUtteranceResult.h>
#include <aws/lexv2-runtime/model/StartConversationHandler.h>
#include <aws/lexv2-runtime/model/StartConversationRequest.h>
#include <aws/lexv2-runtime/model/StartConversationRequestEventStream.h>
#include <aws/lex/LexRuntimeServiceClient.h>
#include <aws/lex/LexRuntimeServiceRequest.h>
#include <aws/lex/model/PostContentRequest.h>
#include <aws/lex/model/PostContentResult.h>
#include <iterator>
#include <fstream>
#include <chrono>
#include <unistd.h>
using namespace Aws::LexRuntimeV2;
int SessionCount = 0;
int main(int argc, char* argv[])
{
std::string lexKey, lexSecret;
std::string botId, botAliasId, localeId, sessionId, regionId;
// bot credentials
botId = "_";
botAliasId = "_";
lexKey = "_";
lexSecret = "_";
localeId = "en_US";
// starting api
Aws::SDKOptions options;
options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Info;
Aws::InitAPI(options);
Aws::Client::ClientConfiguration config;
config.region = "us-east-1";
// creating a lex client
auto lexClient = Aws::MakeUnique<LexRuntimeV2Client>("MyClient", Aws::Auth::AWSCredentials(lexKey.c_str(), lexSecret.c_str()), config);
Model::StartConversationRequest LexRequest;
Model::StartConversationHandler requestHandler;
requestHandler.SetTranscriptEventCallback([](const Model::TranscriptEvent& ev)
{
std::cout << ev.GetTranscript() << std::endl;
});
requestHandler.SetOnErrorCallback([](const Aws::Client::AWSError<LexRuntimeV2Errors>& error)
{
std::cout << "Request handler: " << error.GetMessage() << std::endl;
});
LexRequest.WithLocaleId(localeId).WithBotId(botId.c_str()).WithBotAliasId(botAliasId.c_str()).WithSessionId("Blah")
.WithConversationMode(Model::ConversationMode::AUDIO).WithEventStreamHandler(requestHandler);
Aws::Utils::Threading::Semaphore signaling(0 /*initialCount*/, 1 /*maxCount*/);
auto OnResponseCallback = [&signaling](const LexRuntimeV2Client*,const Model::StartConversationRequest&,
const Model::StartConversationOutcome& outcome, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&)
{
std::cout << "Response handler: " << outcome.GetError().GetMessage();
signaling.Release();
};
Model::StartConversationRequestEventStream* pStream = nullptr;
Aws::Utils::Threading::Semaphore starting(0 /*initialCount*/, 1 /*maxCount*/);
auto OnStreamReady = [&starting,&pStream](Model::StartConversationRequestEventStream& stream)
{
pStream = &stream;
pStream->SetSignatureSeed("blah");
starting.Release();
};
lexClient->StartConversationAsync(LexRequest, OnStreamReady, OnResponseCallback, nullptr);
starting.WaitOne();
std::ifstream audioFile(argv[1], std::ios_base::binary);
if (!audioFile)
{
std::cout << "Cannot open audio file " << argv[2] << std::endl;
return 0;
}
if (audioFile) {
std:: cout << "Audio file is open: "<< std::endl;
}
while (!audioFile.eof())
{
unsigned char buf[320 + 1];
audioFile.read((char*)buf, 320);
Aws::Utils::ByteBuffer bytes(buf, audioFile.gcount());
Model::AudioInputEvent input;
auto millisec_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock().now().time_since_epoch()).count();
input.SetClientTimestampMillis(millisec_since_epoch);
input.SetAudioChunk(bytes);
input.SetContentType("audio/lpcm; sample-rate=8000; sample-size-bits=16; channel-count=1; is-big-endian=false");
pStream->WriteAudioInputEvent(input); // o erro está aqui (quando comento o StartConversation)
sleep(20);
}
signaling.WaitOne(); // prevent the application from exiting until we're done
Aws::ShutdownAPI(options);
}
//g++ -o main main.cpp -laws-cpp-sdk-s3 -laws-cpp-sdk-core -laws-cpp-sdk-lex -laws-cpp-sdk-lex-models -laws-cpp-sdk-lexv2-models -laws-cpp-sdk-lexv2-runtime
debug log](https://i.stack.imgur.com/tpA9c.png)
I have no idea why this is happening, and without this command i obviously can't publish events to lex, since the connection does not have started
I've made several attemps at getting this working to no avail. The program compiles but every timestamp format I can think of for supplying to the program is invalid.
#include <boost/program_options.hpp>
#include <boost/optional.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
#include <string>
using namespace boost::program_options;
using namespace std;
int main(int argc, const char** argv) {
boost::posix_time::ptime forceDate;
boost::optional<boost::posix_time::ptime> forceDateOptional;
options_description descr("Options");
descr.add_options()
("force-date,a", value(&forceDate)->value_name("<date>"), "...");
try {
variables_map args;
store(command_line_parser(argc, argv).options(descr).run(), args);
notify(args);
cout << "Done." << endl;
return 0;
} catch (std::exception& e) {
cerr << e.what() << endl;
return 1;
}
}
Compiled with g++ -I /usr/local/include -L /usr/local/lib -lboost_program_options -lboost_system x.cpp and run with ./a.out --force-date 2012-01-03.
Here is the error from the exception thrown:
the argument ('2012-01-03') for option '--force-date' is invalid
Let's first try to simplify your example by removing program_options and simply trying to parse posix_time::ptime from a stream.
boost::posix_time::ptime forceDate;
std::istringstream ss("2012-01-03");
if(ss >> forceDate) {
std::cout << forceDate << "\n";
}
The above example prints nothing, so clearly something's going wrong with the parsing. If you look up the documentation for operator>> it becomes evident that the expected format for the month is an abbreviated name instead of a numeric value.
If you change the above code to
boost::posix_time::ptime forceDate;
std::istringstream ss("2012-Jan-03");
if(ss >> forceDate) {
std::cout << forceDate << "\n";
}
it produces the desired output.
More digging through the documentation shows the way to control the input format is using boost::posix_time::time_input_facet. The set_iso_extended_format sets the format to the numeric format you want to use.
boost::posix_time::ptime forceDate;
std::istringstream ss("2012-01-03");
auto facet = new boost::posix_time::time_input_facet();
facet->set_iso_extended_format();
ss.imbue(std::locale(ss.getloc(), facet));
if(ss >> forceDate) {
std::cout << forceDate << "\n";
}
Live demo
Back to program_options now. It doesn't look like the library offers locale support directly, so the only way I can get the above solution to work is by messing with the global locale. If you add the following lines to your example, it behaves as you want it to.
auto facet = new boost::posix_time::time_input_facet();
facet->set_iso_extended_format();
std::locale::global(std::locale(std::locale(), facet));
Live demo
I was able to replicate your code and compile it on Ubuntu 14.04-- I got the same results you did. So I passed the date into a std::string and then attempted to construct a boost::posix_time::ptime from that:
#include <boost/program_options.hpp>
#include <boost/optional.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
#include <string>
using namespace boost::program_options;
using namespace std;
int main (int argc, const char ** argv) {
auto dateStr = string {};
auto descr = options_description { "Options" };
descr.add_options ()
("help,h", "produce help message")
("date,a", value (&dateStr)->value_name ("<date>"), "...");
try {
auto args = variables_map {};
store (command_line_parser (argc, argv).options (descr).run (), args);
notify (args);
auto forceDate = boost::posix_time::ptime { dateStr };
cout << "Done." << endl;
return 0;
} catch (std::exception & e) {
cout << e.what () << endl;
return 1;
}
}
I had to dig around a little before finding out that according to this SO answer you must link boost_date_time. I used the following script to compile and re-run at the same time:
rerun.sh
#!/bin/bash
g++ -o main.x64 -std=c++11 -I . -L/usr/lib/x86_64-linux-gnu main.cpp -lboost_program_options -lboost_system -lboost_date_time
./main.x64 --date "2012-01-01"
and this is the final code I used to get it to run:
main.cpp
#include <boost/program_options.hpp>
#include <boost/optional.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
#include <string>
using namespace boost::program_options;
using namespace boost::posix_time;
using namespace std;
int main (int argc, const char ** argv) {
auto dateStr = string {};
auto descr = options_description { "Options" };
descr.add_options ()
("date,a", value (&dateStr)->value_name ("<date>"), "...");
try {
auto args = variables_map {};
store (command_line_parser (argc, argv).options (descr).run (), args);
notify (args);
// this is the important part.
auto d = boost::gregorian::date {
boost::gregorian::from_simple_string (dateStr)
};
auto forceDate = boost::posix_time::ptime { d };
cout << "Done." << endl;
return 0;
} catch (std::exception & e) {
cout << e.what () << endl;
return 1;
}
}
when i build my own cpprestsdk server and client,i found that when my server receive a request and reply to it, my client have no reaction to it,and it never goes into the breakpoint where i handle the http_response,here is my code;
i was stuck for so many days,will someone help me fix this,thanks a lot
(client send request,server receives it and reply, client fail to receive http_response)
Server(i just got it from somewhere on internet):
#include "cpprest/json.h"
#include "cpprest/http_listener.h"
#include "cpprest/uri.h"
#include "cpprest/asyncrt_utils.h"
#include "cpprest/http_client.h"
using namespace web::http::experimental::listener;
using namespace web::http;
using namespace web;
void handle_get(http_request message)
{
message.reply(status_codes::OK, U("Hello, World!"));
};
void handle_post(http_request message)
{
message.reply(status_codes::NotFound);
};
void handle_put(http_request message)
{
message.reply(status_codes::NotFound);
};
void handle_delete(http_request message)
{
message.reply(status_codes::NotFound);
};
#define TRACE(msg) std::wcout << msg
#define TRACE_ACTION(a, k, v) std::wcout << a << L" (" << k << L", " << v << L")\n"
int main(int argc, char ** argv)
{
uri_builder uri(U("http://localhost:8888"));
http_listener listener(uri.to_uri());
listener.support(methods::GET, handle_get);
listener.support(methods::POST, handle_post);
listener.support(methods::PUT, handle_put);
listener.support(methods::DEL, handle_delete);
try
{
listener
.open()
.then([&listener](){TRACE(L"\nstarting to listen\n"); })
.wait();
while (true);
}
catch (std::exception const & e)
{
std::wcout << e.what() << std::endl;
}
catch (...)
{
std::wcout << "Unknown exception" << std::endl;
}
return 0;
}
and here is my Client
#include "cpprest/http_client.h"
#include "cpprest/filestream.h"
using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams
int main(int argc, char* argv[])
{
auto fileStream = std::make_shared<ostream>();
// Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
http_client client(U("http://www.bing.com/"));
http_client localclient(U("http://localhost:8888"));
return localclient.request(methods::GET);
})
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());
system("pause");
return response.body().read_to_end(fileStream->streambuf());
})
.then([=](size_t)
{
return fileStream->close();
});
try
{
requestTask.wait();
}
catch (const std::exception &e)
{
printf("Error exception:%s\n", e.what());
system("pause");
}
return 0;
}