使用SMTP发送邮件需要用到base64编码和解码,这里是char类型的字符串转换,如果需要编码包括特殊字符的文字,如\0等,请自行修改,将入口参数换成(char* pStr, int iLen), 内部稍作修改。
const unsigned char * base64 = (unsigned char*)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
static CStringA base64encode(CStringA str)
{
CStringA cRet;
int iStrLen = str.GetLength();
int iOutLen = 0;
if (iStrLen % 3 == 0)
{
iOutLen = iStrLen / 3 * 4;
}
else
{
iOutLen = iStrLen /3 * 4 + 4;
}
unsigned char* pBuffer = new unsigned char [iStrLen + 1];
unsigned char* pOut = new unsigned char [iOutLen + 1];
memcpy(pBuffer, str.GetBuffer(0), iStrLen);
str.ReleaseBuffer();
pBuffer[iStrLen] = 0;
memset(pOut, 0, iOutLen);
int i = 0;
int j = 0;
for (i = 0, j = 0; i < iStrLen -3; i += 3, j += 4)
{
pOut[j + 0] = (pBuffer[i] & 0xFC)>>2;
pOut[j + 1] = ((pBuffer[i] & 0x03)<<4) + ((pBuffer[i + 1] &0xF0) >> 4);
pOut[j + 2] = ((pBuffer[i + 1] & 0x0F) << 2) + ((pBuffer[i + 2] & 0xC0) >> 6);
pOut[j + 3] = pBuffer[i + 2] & 0x3F;
}
if (iStrLen % 3 == 1)
{
pOut[j + 0] = (pBuffer[i] & 0xFC) >> 2;
pOut[j + 1] = ((pBuffer[i] & 0x03) << 4);
pOut[j + 2] = 64;
pOut[j + 3] = 64;
j += 4;
}
else if (iStrLen % 3 == 2)
{
pOut[j + 0] = (pBuffer[i] & 0xFC) >> 2;
pOut[j + 1] = ((pBuffer[i] & 0x03) << 4)+((pBuffer[i + 1] & 0xF0) >> 4);
pOut[j + 2] = ((pBuffer[i + 1] & 0x0F) << 2);
pOut[j + 3] = 64;
j+=4;
}
else
{
pOut[j + 0] = (pBuffer[i] & 0xFC)>>2;
pOut[j + 1] = ((pBuffer[i] & 0x03)<<4) + ((pBuffer[i + 1] &0xF0) >> 4);
pOut[j + 2] = ((pBuffer[i + 1] & 0x0F) << 2) + ((pBuffer[i + 2] & 0xC0) >> 6);
pOut[j + 3] = pBuffer[i + 2] & 0x3F;
j += 4;
}
for (int i = 0; i < iOutLen; i++)
{
pOut[i] = base64[pOut[i]];
}
pOut[iOutLen] = 0;
cRet = pOut;
delete [iStrLen + 1] pBuffer;
pBuffer = NULL;
delete [iOutLen + 1] pOut;
pOut = NULL;
return cRet;
}
static CStringA base64decode(CStringA str)
{
CStringA cRet;
int iStrLen = str.GetLength();
int iOutLen = iStrLen * 3 / 4;
unsigned char* pBuffer = new unsigned char [iStrLen + 1];
unsigned char* pOut = new unsigned char [iOutLen + 1];
memcpy(pBuffer, str.GetBuffer(0), iStrLen);
str.ReleaseBuffer();
pBuffer[iStrLen] = 0;
memset(pOut, 0, iOutLen);
CStringA tmp(base64);
for (int i = 0; i < iStrLen; i++)
{
pBuffer[i] = tmp.Find(pBuffer[i]);
}
unsigned char* pEnd = &pBuffer[iStrLen - 1];
while (*pEnd == 64)
{
*pEnd = 0;
pEnd--;
if (pEnd == pBuffer)
{
break;
}
}
int i = 0;
int j = 0;
for(i = 0, j = 0; i < iStrLen; i += 4, j += 3)
{
pOut[j + 0] = (pBuffer[i] << 2) + ((pBuffer[i + 1] & 0x30) >> 4);
pOut[j + 1] = ((pBuffer[i + 1] & 0x0F) << 4) + ((pBuffer[i + 2] & 0x3C) >> 2);
pOut[j + 2] = ((pBuffer[i + 2] & 0x03) << 6) + pBuffer[i + 3];
}
pOut[j] = 0;
cRet = pOut;
delete [iStrLen + 1] pBuffer;
pBuffer = NULL;
delete [iOutLen + 1] pOut;
pOut = NULL;
return cRet;
}