在我看来,MAPI (Windows Mail API)与UTF8有问题(或者我做错了什么)。
代码示例:
HMODULE m_hLib = LoadLibraryA("MAPI32.DLL");
if (m_hLib == NULL)
return SEND_MAIL_CANCELED;
LPMAPISENDMAIL SendMail;
SendMail = (LPMAPISENDMAIL) GetProcAddress(m_hLib, "MAPISendMail");
if (!SendMail)
return;
MapiFileDesc fileDesc;
ZeroMemory(&fileDesc, sizeof(fileDesc));
fileDesc.nPosition = (ULONG) -1;
fileDesc.lpszPathName = (LPSTR) filePath.toUtf8();
fileDesc.lpszFileName = (LPSTR) fileName.toUtf8();
MapiRecipDesc recipientData;
ZeroMemory(&recipientData, sizeof(recipientData));
recipientData.lpszName = (LPSTR) recipient.toUtf8();
recipientData.ulRecipClass = MAPI_TO;
MapiMessage message;
ZeroMemory(&message, sizeof(message));
message.ulReserved = CP_UTF8;
message.lpszSubject = (LPSTR) title.toUtf8();
message.nFileCount = 1;
message.lpFiles = &fileDesc;
message.nRecipCount = 1;
message.lpRecips = &recipientData;
int nError = SendMail(0, NULL, &message, MAPI_LOGON_UI | MAPI_DIALOG, 0);title、filePath、fileName和recipient都是std::string,据我所知,UTF8兼容ASCII码(也是以NULL结尾的),所以它的字符串可以保存这样的值,没有任何问题。
我以这种方式从wstring转换为UTF8:
int requiredSize = WideCharToMultiByte(CP_UTF8, 0, data.c_str(), -1, 0, 0, 0, 0);
if(requiredSize > 0)
{
std::vector<char> buffer(requiredSize);
WideCharToMultiByte(CP_UTF8, 0, data.c_str(), -1, &buffer[0], requiredSize, 0, 0);
this->container.append(buffer.begin(), buffer.end() - 1);
}container是一个std::string对象。
发布于 2012-03-31 03:04:27
MAPISendMail()不支持UTF-8,只支持Ansi。如果你需要发送Unicode数据,你必须在Windows7和更早版本上使用MAPISendMailHelper(),或者在Windows8和更高版本上使用MAPISendMailW()。这在MAPISendMail() documentation中有明确的说明。
注意,当您将cchWideChar参数设置为-1时,WideCharToMultiByte()会包含空终止符。因此,您正在对container数据中的空终止符进行编码并将其包括在内。相反,您应该将cchWideChar设置为字符串的实际长度,以完全避免空终止符:
int requiredSize = WideCharToMultiByte(CP_UTF8, 0, data.c_str(), data.length(), 0, 0, 0, 0);
if (requiredSize > 0)
{
std::vector<char> buffer(requiredSize);
WideCharToMultiByte(CP_UTF8, 0, data.c_str(), data.length(), &buffer[0], requiredSize, 0, 0);
container.append(buffer.begin(), buffer.end());
} 在http://msdn.microsoft.com/en-us/library/windows/desktop/dd296721.aspx上显示“在Windows7及更早版本上:使用MAPISendMailHelper发送消息”,但在http://msdn.microsoft.com/en-us/library/windows/desktop/hh802867.aspx的底部显示“最低支持”为Windows8。这似乎是相互矛盾的信息,因此尚不清楚MAPISendMailHelper是否真的适用于Windows7及更早版本。
https://stackoverflow.com/questions/9943314
复制相似问题