c++ 利用 chilkat 庫發送 html郵件


轉載請註明出處:http://blog.csdn.net/yangyihongyangjiying/article/details/44757687  謝謝!

先簡單介紹一下chilkat庫,chikat是由一家芝加哥公司開發的商業組件,功能比較齊全,詳細介紹可以到官網自行閱讀不是外發產品還是可以用的,chilkat支持多個平臺、語音,詳細請看:http://www.chilkatsoft.com/

c++ 下載地址:http://www.example-code.com/cpp/default.asp  下載時自行認準對應IDE版本,免得出現一些莫名奇怪的bug,類似unresolved external symbol __report_rangecheckfailure這種log可以參考我的博文unresolved external symbol __report_rangecheckfailure 解決思路

下邊是通過chilkat寫下的發送html郵件demo:


static string& trim(std::string &s)   
{  
	if (s.empty())   
	{  
		return s;  
	}  

	s.erase(0,s.find_first_not_of(" "));  
	s.erase(s.find_last_not_of(" ") + 1);  
	return s;  
} 

//注意:當字符串爲空時,也會返回一個空字符串
static void split(string& s, std::string& delim, vector<string >* ret)
{
	size_t last = 0;
	size_t index = s.find_first_of(delim,last);
	while (index != std::string::npos)
	{
		ret->push_back(s.substr(last,index-last));
		last=index+1;
		index=s.find_first_of(delim,last);
	}
	if (index-last>0)
	{
		ret->push_back(s.substr(last,index-last));
	}
}

bool SendHtml(string& sUser, string& sPwd, string& sSmtpHost, 
	string& sSubject, string& sTo, string& sHtmlContent)
{
	CkMailMan mailman;

	//  解鎖設備,CkMailMan 正常使用的前提條件
	bool success = mailman.UnlockComponent("30-day trial");
	if (!success) 
	{
		Log(LOG_INFO, "can not to unlock component.");
	}

	//  設置郵箱服務器,例如:smtp.xx.com
	mailman.put_SmtpHost(sSmtpHost.c_str());

	// 設置郵箱登陸用戶名、密碼
	mailman.put_SmtpUsername(sUser.c_str());
	mailman.put_SmtpPassword(sPwd.c_str());

	CkEmail email;

	// 設置郵件標題
	email.put_Subject(sSubject.c_str());
	// 發送的內容
	email.SetHtmlBody(sHtmlContent.c_str());
	// 發件人
	email.put_From(sUser.c_str());

	// 下邊分割收件人,並逐一添加到CKEMail中
	vector<string> vTos;
	string sSplit = ";";
	split(sTo, sSplit, &vTos);
	vector<string>::iterator iTos = vTos.begin();
	for (; iTos != vTos.end(); iTos ++)
	{
		if (!trim(*iTos).empty())
		{
			// 一次只能添加一個用戶或用戶組
			email.AddTo("",iTos->c_str());
		}
	}

	// 修改郵件編碼格式爲utf8,這個很重要,不然有些中文字符將無法很好顯示
	email.put_Charset("utf8");

	success = mailman.SendEmail(email);
	if (!success) {
		Log(LOG_ERROR, "error happen to send email:%s!", mailman.lastErrorText());
		return false;
	}

	// 最後關閉鏈接
	success = mailman.CloseSmtpConnection();
	if (success != true) {
		Log(LOG_INFO,"Connection to SMTP server not closed cleanly.");
	}

	return true;
}


這裏務必提醒一下,如果郵件中包含中文,必須通過email.put_Charset("utf8"); 將郵件的編碼格式轉爲utf8,這樣那些無法通過ascii碼編碼的中文才能正常顯示出來。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章