用C++发送HTML格式电子邮件的简单方法



我有一个HTML表单,它目前接受输入并以HTML格式在电子邮件中发送,因此电子邮件基本上看起来像表单网页,但所有字段都已填写。

<form method="post" action="/cgi-bin/perlscript.pl" enctype="x-www-form-encoded" name="Form">
   <input type="text" name="txtMyText" id="txtMyText" />
</form>

动作后脚本是用Perl编写的,我目前正在将其转换为C++,因为这样我更容易阅读和维护。此外,我认为它对未来的添加更加灵活。

在Perl中,我可以使用"SendMail"发送电子邮件,并且我可以做这样的事情:

sub PrintStyles
{
print MAIL <<ENDMAIL
<html>
    <head>
        <style>
        h1.title { color: Red; }
        h3.title { color : Black; background-color: yellow; }
        </style>
<!-- Put any valid HTML here that you want -->
<!-- You can even put variables ($xxxx) into the HTML as well, like this: -->
                <td>$myVariable</td>
ENDMAIL
}

这样做的好处是,我可以直接复制和粘贴我的整个CSS和HTML文件(非常长),只要它们位于"ENDMAIL"标记之间,它们就会完美地显示出来。我甚至可以把变量放在那里,而不需要做任何额外的工作。

我的问题是:有没有一个C++库具有类似的功能 我真的觉得我负担不起这样的事情:

cout << "<html>" << endl;
cout << "<head>" << endl;
cout << "......" << endl;

我希望它比较轻。

谢谢。

据我所知,最简单的方法是使用POCO C++库中的SMTPClientSession类。这里有一个很好的例子。

您可以将文本定义为const char *,这将减轻通过cout:输出每一行的痛苦

const char email_text[] =
"<html>n"
"<head>n"
"....";
cout.write(email_text, sizeof(email_text) - 1);
cout.flush();
std::string email_string(email_text);
cout << email_text;
cout.flush();

我还没有使用这个库,但我猜您需要传递一个std::stringchar *

您可以考虑模拟

C++不支持here文档
你需要使用一个字符串并将其发送到你想要的流:

void PrintStyles(ostream& mailstream)
{
    mailstream <<  
    "<html>n"
    "    <head>n"
    "        <style>n"
    "        h1.title { color: Red; }n"
    "        h3.title { color : Black; background-color: yellow; }n"
    "        </style>n"
    "n"
    "<!-- Put any valid HTML here that you want -->n"
    "<!-- You can even put variables (" << xxxx << ") into the HTML as well, like this: -->n"
    "                <td>" << myVariable << "</td>n"
    "n"
    "n";
}

您是否收到来自的邮件流将取决于您使用的电子邮件包。

感谢大家的回复。我决定简单地从代码中调用Perl脚本,并将响应数据作为参数发送。我知道这可能不是最好的解决方案,但我认为我的C++选项不值得。

// Retrieve the POST data    
char* contentLength = getenv{"CONTENT_LENGTH"};
int contentSize     = atoi(contentLength);
char* contentBuffer = (char*)malloc(contentSize);
fread(contentBuffer, 1, contentSize, stdin);
string data         = contentBuffer;
// Execute "sendmail.pl" script
string perlFile     = "sendmail.pl";
string command      = "perl " + perlFile + " "" + data + """;
system(command.c_str());

最新更新