关于imap协议的介绍,在网络中有很多资料。要是更好的掌握还是参考《RFC3501》协议文档。
本文只做简单的使用介绍,分为在telnet中使用和在c++代码中调用。
telnet 命令行中使用imap:
telnet imap.sina.com 143 // 链接端口为143的新浪imap协议邮件服务器
A01 LOGIN user@sina.com password // LOGIN命令 账号 密码 登录服务器
A02 LIST "" * // 列出邮箱中所有信箱
A03 EXAMINE INBOX // 查看收件箱
A04 Search ALL // 查询收件箱所有邮件,可根据参数进行多条件查询
A05 Fetch 6 rfc822 // 接收第6封邮件的完整内容
A06 LOGOUT // 退出
更多命令的使用参考RFC文档 或 telnet测试邮箱imap服务器 IMAP命令学习
c++代码中使用IMAP协议:
socket.h
#ifndef SOCKET_H
#define SOCKET_H
#include <iostream>
#include <QString>
const int BUFSIZ = 4096;
class Socket
{
public:
Socket();
~Socket();
void close();
bool connect(const char *hostNmae, const int& port);
int recv();
void send(const char* request);
friend std::ostream& operator<<( std::ostream& out, const Socket& that)
{
out << that.m_buff;
return out;
}
private:
int m_fd; // 通讯套接字
char m_buff[BUFSIZ]; // 存放缓存数据
};
#endif // SOCKET_H
socket.cpp
#include "socket.h"
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
Socket::Socket()
{
m_fd = socket(AF_INET, SOCK_STREAM, 0);
}
Socket::~Socket()
{
close();
}
void Socket::close()
{
if(m_fd != -1)
{
::close(m_fd);
m_fd = -1;
}
}
bool Socket::connect(const char* hostNmae, const int &port)
{
if(!hostNmae || port < 1 || m_fd < 0)
return false;
sockaddr_in server;
server.sin_family = AF_INET;
hostent* hostInfo = gethostbyname(hostNmae);
if(!hostInfo)
return false;
memcpy( &(server.sin_addr), (struct in_addr*)hostInfo->h_addr_list[0], hostInfo->h_length );
server.sin_port = htons(port);
if( ::connect(m_fd, (sockaddr*)&server,sizeof(server)) == -1 )
return false;
recv();
return true;
}
int Socket::recv()
{
bzero(m_buff,BUFSIZ);
return ::read(m_fd,m_buff,BUFSIZ);
}
void Socket::send(const char *request)
{
::send(m_fd,request,strlen(request),0);
return;
}
main.cpp
#include <QCoreApplication>
#include "socket.h"
#include <iostream>
void request(Socket& sock ,const char* str)
{
std::cout << "client send : " << str << std::endl;
sock.send(str);
bool flag = true;
while( sock.recv() == BUFSIZ )
{
flag = false;
std::cout << sock << std::endl;
}
if(flag)
std::cout << sock << std::endl;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Socket s;
if( !s.connect("imap.sina.com",143))
{
std::cout << "connect error ..." << std::endl;
return -1;
}
request(s ,"a001 login username@sina.com password\r\n");
request(s ,"a002 list \"\" *\r\n");
request(s ,"a003 select inbox\r\n");
request(s ,"a004 search all\r\n");
request(s ,"a005 fetch 6 body[text]\r\n");
return a.exec();
}
还可以通过libcurl库对IMAP协议进行处理参考官方文档:libcurl-源代码示例