2011-05-24 20 views
1

我有一個HTML表單,目前接受輸入併發送出一個HTML格式的電子郵件,使電子郵件看起來基本上像表單網頁,但所有的領域填寫。簡單的方法發送HTML格式的電子郵件在C++

<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; 

我想它是相當輕的重量。

謝謝。

+1

C/C++不支持['here''](http://en.wikipedia.org/wiki/Here_document)文件。它需要是一個帶引號的字符串。但編譯器會自動連接源文件中的多個字符串。 – 2011-05-24 18:39:00

+1

不要使用'endl'。只需使用''\ n''。速度更快,就像便攜式一樣。 – Omnifarious 2011-05-24 18:53:17

+1

在C++中必須有一個好的模板庫來生成電子郵件正文。您需要一個漂亮的MIME庫來生成電子郵件本身,但HTML消息的主體應該由模板引擎完成。 – Omnifarious 2011-05-24 21:11:09

回答

1

謝謝大家的回覆。我決定簡單地從我的代碼中調用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()); 
1

您可以定義文本作爲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 *

1

C++不支持這裏的文件。
您需要使用字符串,並將其發送到你想要的流:

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"; 
} 

是你的郵件流從將取決於您所使用的電子郵件軟件包。

+0

謝謝你的鏈接。我對「這裏的文件」這個詞不熟悉。 – Eric 2011-05-24 23:40:08