国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++實現含附件的郵件發送功能

2020-01-26 13:42:09
字體:
來源:轉載
供稿:網友

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"http://#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] = '/0';  return result; } int Csmtp::SendAttachment(SOCKET &sockClient) /*發送附件*/ {  for (std::vector<string>::iterator iter = filename.begin();iter != filename.end(); iter++)  {   cout << "Attachment is sending??? " << endl;   string path=*iter;  ifstream ifs(path, ios::in | ios::binary); //'或鏈接2個屬性,以輸入、二進制打開'  if (false == ifs.is_open())   {    cout<<"無法打開文件!"<<endl;   return 1;   }   string sendstring;   sendstring = "--@boundary@/r/nContent-Type: application/octet-stream; name=/"1.jpg/"/r/n";   sendstring += "Content-Disposition: attachment; filename=/"1.jpg/"/r/n";   sendstring += "Content-Transfer-Encoding: base64/r/n/r/n";   send(sockClient, sendstring.c_str(), sendstring.length(), 0);   //infile.read((char*)buffer,sizeof(數據類型));  // get length of file:  ifs.seekg (0, ifs.end);  int length = ifs.tellg();  ifs.seekg (0, ifs.beg);  cout<<"length:"<<length<<endl;  // allocate memory:  char * buffer = new char [length];  // read data as a block:  ifs.read (buffer,length);  ifs.close();  char *pbase;   pbase = base64Encode(buffer, length);   delete[]buffer;   string str(pbase);  delete[]pbase;   str+="/r/n";  int err =send(sockClient, str.c_str(), strlen(str.c_str()), 0);   if (err != strlen(str.c_str()))   {    cout << "文件傳送出錯!" << endl;    return 1;   }  } return 0;} bool Csmtp::CReateSocket() {  WSADATA wsaData;  WORD wVersionRequested = MAKEWORD(2, 1);  //WSAStarup,即WSA(Windows SocKNDs Asynchronous,Windows套接字異步)的啟動命令 int err = WSAStartup(wVersionRequested, &wsaData);  cout<<"WSAStartup(0:successful):"<<err<<endl; char namebuf[128]; //獲得本地計算機名 string ip_list; if(0==gethostname(namebuf,128))  {   struct hostent* pHost; //獲得本地IP地址  pHost=gethostbyname(namebuf); //pHost返回的是指向主機的列表  for (int i=0;pHost!=NULL&&pHost->h_addr_list[i]!=NULL;i++)   {   string tem = inet_ntoa(*(struct in_addr *)pHost->h_addr_list[i]);   ip_list += tem;   ip_list += "/n";  }  }  else  {   cout<<"獲取主機信息失敗..."<<endl ;  } ////////////////////////////////////////////////////////////////////////// title=namebuf;// 郵件標題 content=ip_list; //主機ip sockClient = socket(AF_INET, SOCK_STREAM, 0); //建立socket對象  pHostent = gethostbyname(domain.c_str()); //得到有關于域名的信息 if (pHostent == NULL) {  printf( "創建連接失敗,也許沒聯網!/n" );  return false; } return true;}int Csmtp::SendMail(){ char *ecode; char buff[500]; //recv函數返回的結果 int err = 0;  string message; // SOCKADDR_IN addrServer; //服務端地址 addrServer.sin_addr.S_un.S_addr = *((DWORD *)pHostent->h_addr_list[0]); //得到smtp服務器的網絡字節序的ip地址   addrServer.sin_family = AF_INET;  addrServer.sin_port = htons(port); //連接端口25  //int connect (SOCKET s , const struct sockaddr FAR *name , int namelen ); err = connect(sockClient, (SOCKADDR*)&addrServer, sizeof(SOCKADDR)); //向服務器發送請求  cout<<"connect:"<<err<<endl; //telnet smtp.126.com 25 連接服務器結束 buff[recv(sockClient, buff, 500, 0)]='/0'; //cout<<"connect:"<<buff<<endl; message="ehlo 126.com/r/n"; send(sockClient, message.c_str(), message.length(), 0);  buff[recv(sockClient, buff, 500, 0)]='/0'; //cout<<"helo:"<<buff<<endl; message="auth login /r/n"; send(sockClient, message.c_str(), message.length(), 0);  buff[recv(sockClient, buff, 500, 0)]='/0'; //cout<<"auth login:"<<buff<<endl; //上傳郵箱名 message=user;  ecode = base64Encode(message.c_str(), strlen(message.c_str()));  message = ecode;  message += "/r/n";  delete[]ecode;  send(sockClient, message.c_str(), message.length(), 0);  buff[recv(sockClient, buff, 500, 0)]='/0'; //cout<<"usrname:"<<buff<<endl; //上傳郵箱密碼 message=pass;  ecode = base64Encode(message.c_str(), strlen(message.c_str()));  message = ecode;  delete[]ecode;  message += "/r/n";  send(sockClient, message.c_str(), message.length(), 0);  buff[recv(sockClient, buff, 500, 0)]='/0'; //cout<<"password:"<<buff<<endl; message="mail from:<"+user+">/r/nrcpt to:<"+target+">/r/n"; send(sockClient, message.c_str(), message.length(), 0);  buff[recv(sockClient, buff, 500, 0)]='/0'; //cout<<"mail from: "<<buff<<endl; buff[recv(sockClient, buff, 500, 0)]='/0'; //cout<<"rcpt to: "<<buff<<endl; message="data/r/n";//data要單獨發送一次 send(sockClient, message.c_str(), message.length(), 0);  buff[recv(sockClient, buff, 500, 0)]='/0'; //cout<<"data: "<<buff<<endl; ///-----------------------------------------DATA------------------------------------- //要使用Csmtp 發送附件, 需要對Csmtp 頭信息進行說明, 改變Content-type 及為每一段正文添加BOUNDARY 名, cout<<"-------------------DATA------------------------"<<endl; // 頭 message="from:"+user+"/r/nto:"+target+"/r/nsubject:"+title+"/r/n"; message += "MIME-Version: 1.0/r/n";  message += "Content-Type: multipart/mixed;boundary=@boundary@/r/n/r/n";  send(sockClient, message.c_str(), message.length(), 0);  // 正文 message = "--@boundary@/r/nContent-Type: text/plain;charset=/"gb2312/"/r/n/r/n"+content+"/r/n/r/n";  send(sockClient, message.c_str(), message.length(), 0);  //------------------------------------------------------------------------------------------------ // 發送附件 SendAttachment(sockClient); /*發送結尾信息*/   message = "--@boundary@--/r/n./r/n";  send(sockClient, message.c_str(), message.length(), 0);  buff[recv(sockClient, buff, 500, 0)]='/0'; //cout<<"end_qwertyuiop:"<<buff<<endl; message="QUIT/r/n";  send(sockClient, message.c_str(), message.length(), 0);  buff[recv(sockClient, buff, 500, 0)]='/0'; cout<<"Send mail is finish:"<<buff<<endl; return 0;}

容易理解的簡化版可以點擊->這里

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 水富县| 安福县| 铜鼓县| 龙海市| 乌什县| 南木林县| 丰台区| 碌曲县| 亳州市| 东兴市| 金堂县| 白城市| 呼伦贝尔市| 乌拉特中旗| 永丰县| 西丰县| 舟曲县| 潮安县| 平武县| 垣曲县| 绥江县| 慈溪市| 商洛市| 乌兰县| 连江县| 湘潭市| 渭南市| 巨鹿县| 万全县| 凤冈县| 宜州市| 凤阳县| 绩溪县| 久治县| 宜昌市| 三门县| 百色市| 宣恩县| 千阳县| 廉江市| 云安县|