C++實(shí)現(xiàn)含附件的郵件發(fā)送功能
C++實(shí)現(xiàn)郵件發(fā)送程序在vs2013測(cè)試通過,一共3個(gè)文件,發(fā)郵件的程序封裝為Csmtp 類。
1.測(cè)試用的主函數(shù)
// #include "Csmtp.h" #pragma comment(lib, "Kernel32.lib") int main() { Csmtp mail( 25, "smtp.126.com", "username@126.com",// 來(lái)源郵箱 "pwd", "username@126.com" //目標(biāo)郵箱 ); 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(); //類主函數(shù) return 0; }
2.Csmtp類定義
#include <iostream> #include <string> #include <vector> #include <fstream> #include <WinSock2.h> //適用平臺(tái) Windows #pragma comment(lib, "ws2_32.lib") /*鏈接ws2_32.lib動(dòng)態(tài)鏈接庫(kù)*/ // POP3服務(wù)器(端口:110) Csmtp服務(wù)器(端口:25) using namespace std; class Csmtp { int port; string domain; string user; string pass; string target; string title; //郵件標(biāo)題 string content; //郵件內(nèi)容 HOSTENT* pHostent; SOCKET sockClient; //客戶端的套接字 vector <string> filename; //存儲(chǔ)附件名的向量 public: Csmtp( int _port, //端口25 string _domain, //域名 string _user, //發(fā)送者的郵箱 string _pass, //密碼 string _target) //目標(biāo)郵箱 :port(_port),domain(_domain),user(_user),pass(_pass), target(_target){};//內(nèi)容 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 類的實(shí)現(xiàn)
#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] = '\0'; return result; } int Csmtp::SendAttachment(SOCKET &sockClient) /*發(fā)送附件*/ { 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個(gè)屬性,以輸入、二進(jìn)制打開' if (false == ifs.is_open()) { cout<<"無(wú)法打開文件!"<<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(數(shù)據(jù)類型)); // 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 << "文件傳送出錯(cuò)!" << endl; return 1; } } return 0; } bool Csmtp::CReateSocket() { WSADATA wsaData; WORD wVersionRequested = MAKEWORD(2, 1); //WSAStarup,即WSA(Windows SocKNDs Asynchronous,Windows套接字異步)的啟動(dòng)命令 int err = WSAStartup(wVersionRequested, &wsaData); cout<<"WSAStartup(0:successful):"<<err<<endl; char namebuf[128]; //獲得本地計(jì)算機(jī)名 string ip_list; if(0==gethostname(namebuf,128)) { struct hostent* pHost; //獲得本地IP地址 pHost=gethostbyname(namebuf); //pHost返回的是指向主機(jī)的列表 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<<"獲取主機(jī)信息失敗..."<<endl ; } ////////////////////////////////////////////////////////////////////////// title=namebuf;// 郵件標(biāo)題 content=ip_list; //主機(jī)ip sockClient = socket(AF_INET, SOCK_STREAM, 0); //建立socket對(duì)象 pHostent = gethostbyname(domain.c_str()); //得到有關(guān)于域名的信息 if (pHostent == NULL) { printf( "創(chuàng)建連接失敗,也許沒聯(lián)網(wǎng)!\n" ); return false; } return true; } int Csmtp::SendMail() { char *ecode; char buff[500]; //recv函數(shù)返回的結(jié)果 int err = 0; string message; // SOCKADDR_IN addrServer; //服務(wù)端地址 addrServer.sin_addr.S_un.S_addr = *((DWORD *)pHostent->h_addr_list[0]); //得到smtp服務(wù)器的網(wǎng)絡(luò)字節(jié)序的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)); //向服務(wù)器發(fā)送請(qǐng)求 cout<<"connect:"<<err<<endl; //telnet smtp.126.com 25 連接服務(wù)器結(jié)束 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要單獨(dú)發(fā)送一次 send(sockClient, message.c_str(), message.length(), 0); buff[recv(sockClient, buff, 500, 0)]='\0'; //cout<<"data: "<<buff<<endl; ///-----------------------------------------DATA------------------------------------- //要使用Csmtp 發(fā)送附件, 需要對(duì)Csmtp 頭信息進(jìn)行說明, 改變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); //------------------------------------------------------------------------------------------------ // 發(fā)送附件 SendAttachment(sockClient); /*發(fā)送結(jié)尾信息*/ 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; }
容易理解的簡(jiǎn)化版可以點(diǎn)擊->這里
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
上一篇:簡(jiǎn)單實(shí)現(xiàn)C語(yǔ)言2048游戲
欄 目:C語(yǔ)言
下一篇:C語(yǔ)言中system()執(zhí)行cmd命令打開關(guān)閉程序的方法
本文標(biāo)題:C++實(shí)現(xiàn)含附件的郵件發(fā)送功能
本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/794.html
您可能感興趣的文章
- 04-02c語(yǔ)言沒有round函數(shù) round c語(yǔ)言
- 01-10數(shù)據(jù)結(jié)構(gòu)課程設(shè)計(jì)-用棧實(shí)現(xiàn)表達(dá)式求值的方法詳解
- 01-10使用OpenGL實(shí)現(xiàn)3D立體顯示的程序代碼
- 01-10深入理解C++中常見的關(guān)鍵字含義
- 01-10求斐波那契(Fibonacci)數(shù)列通項(xiàng)的七種實(shí)現(xiàn)方法
- 01-10C語(yǔ)言 解決不用+、-、&#215;、&#247;數(shù)字運(yùn)算符做加法
- 01-10使用C++實(shí)現(xiàn)全排列算法的方法詳解
- 01-10c++中inline的用法分析
- 01-10用C++實(shí)現(xiàn)DBSCAN聚類算法
- 01-10深入全排列算法及其實(shí)現(xiàn)方法


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 04-02c語(yǔ)言函數(shù)調(diào)用后清空內(nèi)存 c語(yǔ)言調(diào)用
- 04-02func函數(shù)+在C語(yǔ)言 func函數(shù)在c語(yǔ)言中
- 04-02c語(yǔ)言的正則匹配函數(shù) c語(yǔ)言正則表達(dá)
- 04-02c語(yǔ)言用函數(shù)寫分段 用c語(yǔ)言表示分段
- 04-02c語(yǔ)言中對(duì)數(shù)函數(shù)的表達(dá)式 c語(yǔ)言中對(duì)
- 04-02c語(yǔ)言編寫函數(shù)冒泡排序 c語(yǔ)言冒泡排
- 04-02c語(yǔ)言沒有round函數(shù) round c語(yǔ)言
- 04-02c語(yǔ)言分段函數(shù)怎么求 用c語(yǔ)言求分段
- 04-02C語(yǔ)言中怎么打出三角函數(shù) c語(yǔ)言中怎
- 04-02c語(yǔ)言調(diào)用函數(shù)求fibo C語(yǔ)言調(diào)用函數(shù)求
隨機(jī)閱讀
- 04-02jquery與jsp,用jquery
- 01-10delphi制作wav文件的方法
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 01-10C#中split用法實(shí)例總結(jié)
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置