C++实现邮件发送程序在vs2013测试通过,一共3个文件,发邮件的程序封装为Csmtp 类。
1.测试用的主函数
//
#include "Csmtp.h"
#pragma comment(lib, "Kernel32.lib")
int main()
{
Csmtp mail(
25,
"smtp.126.com",
"username@126.com",// 来源邮箱
"pwd",
"username@126.com" //目标邮箱
);
if (!mail.CReateSocket())
{
cout << "ReateSocket failed!" << endl;
return -1;//
}
mail.setTitle("test mail");
mail.setContent("this is content.");
mail.addfile("test1.png"); //添加附件
mail.addfile("test2.png"); //添加附件
mail.SendMail(); //类主函数
return 0;
}
2.Csmtp类定义
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <WinSock2.h> //适用平台 Windows
#pragma comment(lib, "ws2_32.lib") /*链接ws2_32.lib动态链接库*/
// POP3服务器(端口:110) Csmtp服务器(端口:25)
using namespace std;
class Csmtp
{
int port;
string domain;
string user;
string pass;
string target;
string title; //邮件标题
string content; //邮件内容
HOSTENT* pHostent;
SOCKET sockClient; //客户端的套接字
vector <string> filename; //存储附件名的向量
public:
Csmtp(
int _port, //端口25
string _domain, //域名
string _user, //发送者的邮箱
string _pass, //密码
string _target) //目标邮箱
:port(_port),domain(_domain),user(_user),pass(_pass), target(_target){};//内容
bool CReateSocket();
void setTitle(string tem){title = tem;}
void setContent(string tem){content = tem;}
int SendAttachment(SOCKET &sockClient);
int SendMail();
void addfile(string str){filename.push_back(str);}
};
3. Csmtp 类的实现
#include "Csmtp.h"
//#include <afx.h>//异常类
static const char base64Char[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char* base64Encode(char const* origSigned, unsigned origLength)
{
unsigned char const* orig = (unsigned char const*)origSigned; // in case any input bytes have the MSB set
if (orig == NULL) return NULL;
unsigned const numOrig24BitValues = origLength / 3;
bool havePadding = origLength > numOrig24BitValues * 3;
bool havePadding2 = origLength == numOrig24BitValues * 3 + 2;
unsigned const numResultBytes = 4 * (numOrig24BitValues + havePadding);
char* result = new char[numResultBytes + 3]; // allow for trailing '/0'
// Map each full group of 3 input bytes into 4 output base-64 characters:
unsigned i;
for (i = 0; i < numOrig24BitValues; ++i)
{
result[4 * i + 0] = base64Char[(orig[3 * i] >> 2) & 0x3F];
result[4 * i + 1] = base64Char[(((orig[3 * i] & 0x3) << 4) | (orig[3 * i + 1] >> 4)) & 0x3F];
result[4 * i + 2] = base64Char[((orig[3 * i + 1] << 2) | (orig[3 * i + 2] >> 6)) & 0x3F];
result[4 * i + 3] = base64Char[orig[3 * i + 2] & 0x3F];
}
// Now, take padding into account. (Note: i == numOrig24BitValues)
if (havePadding)
{
result[4 * i + 0] = base64Char[(orig[3 * i] >> 2) & 0x3F];
if (havePadding2)
{
result[4 * i + 1] = base64Char[(((orig[3 * i] & 0x3) << 4) | (orig[3 * i + 1] >> 4)) & 0x3F];
result[4 * i + 2] = base64Char[(orig[3 * i + 1] << 2) & 0x3F];
}
else
{
result[4 * i + 1] = base64Char[((orig[3 * i] & 0x3) << 4) & 0x3F];
result[4 * i + 2] = '=';
}
result[4 * i + 3] = '=';
}
result[numResultBytes] = '
