博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
POP3邮件接收
阅读量:5095 次
发布时间:2019-06-13

本文共 8918 字,大约阅读时间需要 29 分钟。

添加邮件实体

///     /// 收到的邮件实体    ///     public class MailInfo    {        ///         /// 发件地址        ///         public string From        {            get;            set;        }        ///         /// 收件地址        ///         public string To        {            get;            set;        }        ///         /// 发件日期        ///         public DateTime Date        {            get;            set;        }        ///         /// 内容        ///         public string Content        {            get;            set;        }    }

Pop3协议使用的是110端口,使用pop3连接邮件服务器首先要用TcpClient与邮件服务器建议一个连接,向流中写命令,然后可读取流中邮件服务器写入的返回信息。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.Net;using System.Net.Sockets;namespace Email.Pop3{    ///     /// 读取邮件客户端    ///     public class Pop3Client    {        private TcpClient Server;        private NetworkStream NetStrm;        private StreamReader RdStrm;        private string Data;        private byte[] szData;        private string CRLF = "\r\n";        ///         /// 收件箱中邮件数量        ///         private int mailCount;        private bool conn = false;        ///         /// 是否已连接        ///         public bool Connected        {            get { return conn; }        }        ////         /// 连接邮件服务器        ///         /// 邮件服务器        /// 账号        /// 密码        /// 
是否连接成功
public bool Connect(string server, string account, string passWord) { //用110端口新建POP3服务器连接 Server = new TcpClient(server, 110); try { //初始化 NetStrm = Server.GetStream(); RdStrm = new StreamReader(Server.GetStream()); string init = RdStrm.ReadLine(); //登录服务器过程 Data = "USER " + account + CRLF; szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray()); NetStrm.Write(szData, 0, szData.Length); string user = RdStrm.ReadLine(); Data = "PASS " + passWord + CRLF; szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray()); NetStrm.Write(szData, 0, szData.Length); string pass = RdStrm.ReadLine(); if (pass[0] == '+') { //向服务器发送STAT命令,从而取得邮箱的相关信息:邮件数量和大小 Data = "STAT" + CRLF; szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray()); NetStrm.Write(szData, 0, szData.Length); //依据返回信息,初始化队列大小 string[] inboxParams = RdStrm.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); int.TryParse(inboxParams[1], out mailCount); conn = true; } } catch (InvalidOperationException ex) { conn = false; throw ex; } return conn; } /// /// 断开连接 /// public void DisConnect() { //向服务器发送QUIT命令从而结束和POP3服务器的会话 Data = "QUIT" + CRLF; szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray()); NetStrm.Write(szData, 0, szData.Length); string msg = RdStrm.ReadLine(); //断开连接 NetStrm.Close(); RdStrm.Close(); } /// /// 收信 /// ///
public Queue
Receive() { Queue
mailQueue = new Queue
(); string szTemp; for (int i = 1; i <= mailCount; i++) { //根据邮件编号从服务器获得相应邮件 Data = "RETR " + i + CRLF; szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray()); NetStrm.Write(szData, 0, szData.Length); szTemp = RdStrm.ReadLine(); StringBuilder mailTxt = new StringBuilder(); if (szTemp.Length > 0 && szTemp[0] != '-') { //不断地读取邮件内容,直到结束标志:英文句号 while (szTemp != ".") { mailTxt.Append(szTemp + "\n"); szTemp = RdStrm.ReadLine(); } MailInfo m = new MailInfo() { From = MessageParse.GetFrom(mailTxt.ToString()), To = MessageParse.GetTo(mailTxt.ToString()), Date = MessageParse.GetDate(mailTxt.ToString()), Content = MessageParse.GetContent(mailTxt.ToString()) }; mailQueue.Enqueue(m); } } return mailQueue; } ///
/// 删除读取后的邮件 /// public void Delete() { for (int i = 1; i <= mailCount; i++) { Data = "DELE " + i + CRLF; szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray()); NetStrm.Write(szData, 0, szData.Length); } } }}

读取邮件的标题、内容等需要解析。下面是一个提取邮件标题、内容、发件箱等的解析类。不太完整,仅供参考。

///     /// 读取邮件内容    ///     public class MessageParse    {        ///         /// 获取发件人        ///         ///         /// 
public static string GetFrom(string message) { if (!message.Contains("\nFrom:")) { return string.Empty; } string cutMsg = message.Substring(message.IndexOf("\nFrom:") + 7); cutMsg = cutMsg.Remove(cutMsg.IndexOf("\n")); if (cutMsg.Contains('<') && cutMsg.Contains('>')) { int indexS = cutMsg.IndexOf('<'); int indexE = cutMsg.IndexOf('>'); if (indexE - 1 > indexS) { cutMsg = cutMsg.Substring(indexS + 1, indexE - indexS - 1); } } cutMsg=cutMsg.Trim('>'); cutMsg=cutMsg.Trim('<'); return cutMsg; } /// /// 获取收件人 /// /// ///
public static string GetTo(string message) { if (!message.Contains("\nTo:")) { return string.Empty; } string cutMsg = message.Substring(message.IndexOf("\nTo:") + 5); cutMsg = cutMsg.Remove(cutMsg.IndexOf("\n")); if (cutMsg.Contains('<') && cutMsg.Contains('>')) { int indexS = cutMsg.IndexOf('<'); int indexE = cutMsg.IndexOf('>'); if (indexE - 1 > indexS) { cutMsg = cutMsg.Substring(indexS + 1, indexE - indexS - 1); } } cutMsg=cutMsg.Trim('>'); cutMsg=cutMsg.Trim('<'); return cutMsg; } /// /// 获取收件日期 /// /// ///
public static DateTime GetDate(string message) { if (!message.Contains("\nTo:")) { return DateTime.MinValue; } string cutMsg = message.Substring(message.IndexOf("\nDate:") + 7); cutMsg = cutMsg.Remove(cutMsg.IndexOf("\n")); DateTime time = DateTime.Now; try { time = Convert.ToDateTime(cutMsg); } catch { } return time; } /// /// 获取内容 /// /// ///
public static string GetContent(string message) { if (!message.Contains("\nContent")) { return string.Empty; } string cutMsg = message.Substring(message.LastIndexOf("\nContent")); cutMsg = cutMsg.Substring(cutMsg.IndexOf("\n\n") + 2); if (cutMsg.IndexOf("\n\n") > 0) { cutMsg = cutMsg.Remove(cutMsg.IndexOf("\n\n")); } if (message.Contains("\nContent-Transfer-Encoding: base64")) { if (message.Contains("charset=")) { string charSet = message.Substring(message.LastIndexOf("charset=") + 8); charSet = charSet.Remove(charSet.IndexOf('\n')).Trim('"'); try { Encoding encoding = Encoding.GetEncoding(charSet); cutMsg = Encoding.GetEncoding(charSet).GetString(Convert.FromBase64String(cutMsg)); } catch { try { cutMsg = Encoding.Default.GetString(Convert.FromBase64String(cutMsg)); } catch { } } } } return cutMsg; } }

 

转载于:https://www.cnblogs.com/xingbinggong/archive/2013/04/23/3037838.html

你可能感兴趣的文章
ResolveUrl的用法
查看>>
Linux内核态、用户态简介与IntelCPU特权级别--Ring0-3
查看>>
第23月第24天 git命令 .git-credentials git rm --cached git stash clear
查看>>
GitHub开源:升讯威ADO.NET增强组件 sheng.ADO.NET.Plus V1.3
查看>>
华为离职副总裁徐家骏:年薪千万的工作感悟
查看>>
java SE :标准输入/输出
查看>>
vs 打开项目时要建配置文件的解决办法
查看>>
sublimie 知乎
查看>>
three.js 入门案例
查看>>
一些方便系统诊断的bash函数
查看>>
Floyd算法 - 最短路径
查看>>
【转载】基于vw等viewport视区相对单位的响应式排版和布局
查看>>
<转>关于MFC的多线程类 CSemaphore,CMutex,CCriticalSection,CEvent
查看>>
《你们都是魔鬼吗》实验十二 团队作业八:Alpha冲刺
查看>>
jquery中ajax返回值无法传递到上层函数
查看>>
[Leetcode]942. DI String Match
查看>>
css3之transform-origin
查看>>
1003 Emergency
查看>>
bm25
查看>>
Oracle 导入导出 创建用户等
查看>>