使用SMTP 和POP3 协议实现收发邮件(C/C++)

本文不详述SMTP和POP3协议,而是直接提供一个使用C/C++编写的`Sock`类,该类用于创建套接字并连接邮箱服务器,实现了邮件的发送和接收功能。SMTP协议用于发送邮件,而POP3协议用于接收邮件,但POP3连接可能偶尔被服务器拒绝,多尝试即可解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SMTP协议和POP3协议就不详细阐述了 ,网上一搜索会有一大把给你解释的。


下面直接贴代码:

首先写一个class Sock类,这个类的功能主要是创建套接字(即int sock),用套接字來连接邮箱服务器。类里面还带有send_socket和recv_socket两个函数,其功能分别是向邮箱服务器发送协议指令和接收服务器反馈回来的信息。

sock.h文件

  #ifndef __SOCK_H__
  #define __SOCK_H__
  
  #include <iostream>
  #include <sys/socket.h>
  #include <sys/epoll.h>
  #include <stdio.h>
  #include <netinet/in.h>
  
 class Sock
 {
 public:
     Sock();
      bool Connect(const char *host_id, constint &port);
      void send_socket(const char *s);
      int recv_socket();
      constchar * get_recvbuf();
      ~Sock();
       private:
      char recvbuf[BUFSIZ];
      int sock;
      int num;
      struct sockaddr_in server;
      struct hostent *hp;
   };
  #endif


sock.cpp文件

#include"sock.h"
#include<stdexcept>
#include<netdb.h>
#include<string.h>
#include<sys/types.h>
  
Sock::Sock()
{
     sock= socket(AF_INET, SOCK_STREAM, 0);
      if(sock == -1)
      {
           throw std::runtime_error("socketinit error\n");
      }
}
Sock::~Sock()
 {
      close(sock);
 }
bool Sock::Connect(constchar *host_id, const int &port)
{
      server.sin_family = AF_INET;
      hp = gethostbyname(host_id);
    
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值