问题
I'm using the POCO library in C++ (1.5.2) , and i wonder if it is possible to send HTML code in a mail.
This is the code I'm using for sending email (via my gmail):
#include <iostream>
#include <string>
#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>
int main()
{
Poco::Net::MailMessage mailMessage;
mailMessage.addRecipient(Poco::Net::MailRecipient(Poco::Net::MailRecipient::PRIMARY_RECIPIENT, "user1@gmail.com", "user1"));
mailMessage.setSubject("test");
mailMessage.setSender("myemail@gmail.com");
mailMessage.setContent("Hello, world!\r\n");
Poco::Net::SecureSMTPClientSession session("smtp.gmail.com", 587);
session.open();
Poco::Net::initializeSSL();
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, true, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
Poco::Net::SSLManager::instance().initializeClient(NULL, ptrHandler, ptrContext);
try
{
session.login();
if(session.startTLS(ptrContext))
{
session.login(Poco::Net::SecureSMTPClientSession::AUTH_LOGIN, "myemail@gmail.com", "mypassword");
session.sendMessage(mailMessage);
}
session.close();
Poco::Net::uninitializeSSL();
}
catch(Poco::Net::SMTPException &e)
{
std::cout << e.message() << std::endl;
session.close();
Poco::Net::uninitializeSSL();
}
system("pause");
return 0;
}
Is there any solution for sending an image in my message for example ?
Thank you !!
回答1:
Try something like this when filling in the email content:
#include <Poco\Net\StringPartSource.h>
#include <Poco\Net\FilePartSource.h>
#include <Poco\Net\MailMessage.h>
...
Poco::Net::MailMessage mailMessage;
mailMessage.addRecipient(Poco::Net::MailRecipient(Poco::Net::MailRecipient::PRIMARY_RECIPIENT, "user1@gmail.com", "user1"));
mailMessage.setSubject("test");
mailMessage.setSender("myemail@gmail.com");
Poco::Net::MediaType mediaType("multipart", "related");
mediaType.setParameter("type", "text/html");
mailMessage.setContentType(mediaType);
std::string html = "<html><body>Hello, world!<br><img src=\"cid:image\"></body></html>";
mailMessage.addPart("", new Poco::Net::StringPartSource(html, "text/html"), CONTENT_INLINE, ENCODING_QUOTED_PRINTABLE);
Poco::Net::FilePartSource *image = new Poco::Net::FilePartSource("image.jpg", "image/jpeg");
image->headers().add("Content-ID", "<image>");
mailMessage.addPart("", image, CONTENT_INLINE, ENCODING_BASE64);
来源:https://stackoverflow.com/questions/22438474/sending-html-code-in-a-mail-using-poco-library