发邮件界面:

收邮件界面:

先分析邮件发送类

邮件发送类使用smtp协议,这里以QQ邮箱为例

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//添加的命名空间引用
using System.Net;
using System.Net.Mail;
using System.IO;
using System.Net.Mime; namespace SendMailExample
{
public partial class FormSendMail : Form
{
public FormSendMail()
{
InitializeComponent();
} private void FormSendMail_Load(object sender, EventArgs e)
{
//邮箱协议
textBoxSmtpServer.Text = "smtp.qq.com";
//发送人邮箱
textBoxSend.Text = "邮箱账号";
//发送人姓名
textBoxDisplayName.Text = "名字";
//密码
textBoxPassword.Text = "邮箱密码";
//收件人姓名
textBoxReceive.Text = "收件人邮箱账号";
//发送标题
textBoxSubject.Text = "测试mytest";
//发送内容
textBoxBody.Text = "This is a test(测试)";
radioButtonSsl.Checked = true;
} //单击【发送】按钮触发的事件
private void buttonSend_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
//实例化一个发送邮件类
MailMessage mailMessage = new MailMessage();
//发件人邮箱,方法重载不同,可以根据需求自行选择
mailMessage.From = new MailAddress(textBoxSend.Text, textBoxDisplayName.Text, System.Text.Encoding.UTF8);
//收件人邮箱地址
mailMessage.To.Add(textBoxReceive.Text);
//邮件标题
mailMessage.Subject = textBoxSubject.Text;
//邮件发送使用的编码
mailMessage.SubjectEncoding = System.Text.Encoding.Default;
//邮件发送的内容
mailMessage.Body = textBoxBody.Text;
//发送邮件的标题
mailMessage.BodyEncoding = System.Text.Encoding.Default;
//指定邮件是否为html格式
mailMessage.IsBodyHtml = false;
//设置电子邮件的优先级
mailMessage.Priority = MailPriority.Normal;
//添加附件
Attachment attachment = null;
if (listBoxFileName.Items.Count > )
{
for (int i = ; i < listBoxFileName.Items.Count; i++)
{
string pathFileName = listBoxFileName.Items[i].ToString();
string extName = Path.GetExtension(pathFileName).ToLower();
//这里仅举例说明如何判断附件类型
if (extName == ".rar" || extName == ".zip")
{
attachment = new Attachment(pathFileName, MediaTypeNames.Application.Zip);
}
else
{
attachment = new Attachment(pathFileName, MediaTypeNames.Application.Octet);
}
ContentDisposition cd = attachment.ContentDisposition;
cd.CreationDate = File.GetCreationTime(pathFileName);
cd.ModificationDate = File.GetLastWriteTime(pathFileName);
cd.ReadDate = File.GetLastAccessTime(pathFileName);
mailMessage.Attachments.Add(attachment);
}
}
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = textBoxSmtpServer.Text;
smtpClient.Port = ;
//是否使用安全套接字层加密连接
smtpClient.EnableSsl = radioButtonSsl.Checked;
//不使用默认凭证,注意此句必须放在client.Credentials的上面
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(textBoxSend.Text, textBoxPassword.Text);
//邮件通过网络直接发送到服务器
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
smtpClient.Send(mailMessage);
MessageBox.Show("发送成功");
}
catch (SmtpException smtpError)
{
MessageBox.Show("发送失败:" + smtpError.StatusCode
+ "\n\n" + smtpError.Message
+ "\n\n" + smtpError.StackTrace);
}
finally
{
mailMessage.Dispose();
smtpClient = null;
this.Cursor = Cursors.Default;
}
} //单击【添加附件】按钮触发的事件
private void buttonAddAttachment_Click(object sender, EventArgs e)
{
//提示用户打开一个文件夹
OpenFileDialog myOpenFileDialog = new OpenFileDialog();
myOpenFileDialog.CheckFileExists = true;
//只接收有效的文件名
myOpenFileDialog.ValidateNames = true;
//允许一次选择多个文件作为附件
myOpenFileDialog.Multiselect = true;
myOpenFileDialog.ShowDialog();
if (myOpenFileDialog.FileNames.Length > )
{
listBoxFileName.Items.AddRange(myOpenFileDialog.FileNames);
}
}
}
}

收邮件的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//添加的命名空间引用
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace ReceiveMailExample
{
public partial class FormReceiveMail : Form
{
private TcpClient tcpClient;
private NetworkStream networkStream;
private StreamReader sr;
private StreamWriter sw;
public FormReceiveMail()
{
InitializeComponent();
textBoxPOP3Server.Text = "pop.qq.com";
textBoxPassword.Text = "密码";
textBoxUser.Text = "邮箱账号";
} //单击建立连接按钮触发的事件
private void buttonConnect_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
listBoxStatus.Items.Clear();
try
{
//建立与POP3服务器的连接,使用默认端口110
tcpClient = new TcpClient(textBoxPOP3Server.Text,);
listBoxStatus.Items.Add("与pop3服务器连接成功");
}
catch
{
MessageBox.Show("与服务器连接失败");
return;
}
string str;
networkStream = tcpClient.GetStream();
//得到输入流
sr = new StreamReader(networkStream, Encoding.Default);
//得到输出流
sw = new StreamWriter(networkStream, Encoding.Default);
sw.AutoFlush = true;
//读取服务器回送的连接信息
str = GetResponse();
if (CheckResponse(str) == false) return;
//向服务器发送用户名,请求确认
SendToServer("USER " + textBoxUser.Text);
str = GetResponse();
if (CheckResponse(str) == false) return;
//向服务器发送密码,请求确认
SendToServer("PASS " + textBoxPassword.Text);
str = GetResponse();
if (CheckResponse(str) == false) return;
//向服务器发送LIST命令,请求获取邮件总数和总字节数
SendToServer("LIST");
str = GetResponse();
if (CheckResponse(str) == false) return;
string[] splitString = str.Split(' ');
//从字符串中取子串获取邮件总数
int count = int.Parse(splitString[]);
//判断邮箱中是否有邮件
if (count > )
{
listBoxOperation.Items.Clear();
groupBoxOperation.Text = "信箱中共有 " + splitString[] + " 封邮件";
//向邮件列表框中添加邮件
for (int i = ; i < count; i++)
{
str = GetResponse();
splitString = str.Split(' ');
listBoxOperation.Items.Add(string.Format(
"第{0}封:{1}字节", splitString[], splitString[]));
}
listBoxOperation.SelectedIndex = ;
//读出结束符
str = GetResponse();
//设置对应状态信息
buttonRead.Enabled = true;
buttonDelete.Enabled = true;
}
else
{
groupBoxOperation.Text = "信箱中没有邮件";
buttonRead.Enabled = false;
buttonDelete.Enabled = false;
}
buttonConnect.Enabled = false;
buttonDisconnect.Enabled = true;
Cursor.Current = Cursors.Default;
} private bool SendToServer(string str)
{
try
{
sw.WriteLine(str);
sw.Flush();
listBoxStatus.Items.Add("发送:" + str);
return true;
}
catch (Exception err)
{
listBoxStatus.Items.Add("发送失败:" + err.Message);
return false;
}
} private string GetResponse()
{
string str = null;
try
{
str = sr.ReadLine();
if (str == null)
{
listBoxStatus.Items.Add("收到:null");
}
else
{
listBoxStatus.Items.Add("收到:" + str);
if (str.StartsWith("-ERR"))
{
str = null;
}
}
}
catch (Exception ex)
{
listBoxStatus.Items.Add("接收失败:" + ex.Message);
}
return str;
} private bool CheckResponse(string responseString)
{
if (responseString == null)
{
return false;
}
else
{
if (responseString.StartsWith("+OK"))
{
return true;
}
else
{
return false;
}
}
} //单击断开连接按钮触发的事件
private void buttonDisconnect_Click(object sender, EventArgs e)
{
SendToServer("QUIT");
sr.Close();
sw.Close();
networkStream.Close();
tcpClient.Close();
listBoxOperation.Items.Clear();
richTextBoxOriginalMail.Clear();
listBoxStatus.Items.Clear();
groupBoxOperation.Text = "邮件信息";
buttonConnect.Enabled = true;
buttonDisconnect.Enabled = false;
} //单击阅读信件按钮触发的事件
private void buttonRead_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
richTextBoxOriginalMail.Clear();
string mailIndex = listBoxOperation.SelectedItem.ToString();
mailIndex = mailIndex.Substring(, mailIndex.IndexOf("封") - );
SendToServer("RETR " + mailIndex);
string str = GetResponse();
if (CheckResponse(str) == false) return;
try
{
string receiveData = sr.ReadLine();
if (receiveData.StartsWith("-ERR") == true)
{
listBoxStatus.Items.Add(receiveData);
}
else
{
while (receiveData != ".")
{
richTextBoxOriginalMail.AppendText(receiveData + "\r\n");
receiveData = sr.ReadLine();
}
}
}
catch (InvalidOperationException err)
{
listBoxStatus.Items.Add("Error: " + err.ToString());
}
Cursor.Current = Cursors.Default;
} private void DecodeMailHeader(string mail)
{
string header = "";
int pos = mail.IndexOf("\n\n");
if (pos == -)
{
header = GetDecodedHeader(mail);
}
else
{
header = mail.Substring(, pos + );
}
//richTextBoxDecode.AppendText(GetDecodedHeader(header));
} private string GetDecodedHeader(string header)
{
StringBuilder s = new StringBuilder();
s.AppendLine("Subject:" + GetEncodedValueString(header, "Subject: ", false));
s.AppendLine("From:" + GetEncodedValueString(header, "From: ", false).Trim());
s.AppendLine("To:" + GetEncodedValueString(header, "To: ", true).Trim());
s.AppendLine("Date:" + GetDateTimeFromString(GetValueString(header, "Date: ", false, false)));
s.AppendLine("Cc:" + GetEncodedValueString(header, "Cc: ", true).Trim());
s.AppendLine("ContentType:" + GetValueString(header, "Content-Type: ", false, true));
return s.ToString();
} /// <summary>
/// 把时间转成字符串形式
/// </summary>
/// <param name="DateTimeString"></param>
/// <returns></returns>
private string GetDateTimeFromString(string DateTimeString)
{
if (DateTimeString == "")
{
return null;
}
try
{
string strDateTime;
if (DateTimeString.IndexOf("+") != -)
{
strDateTime = DateTimeString.Substring(, DateTimeString.IndexOf("+"));
}
else if (DateTimeString.IndexOf("-") != -)
{
strDateTime = DateTimeString.Substring(, DateTimeString.IndexOf("-"));
}
else
{
strDateTime = DateTimeString;
}
DateTime dt = DateTime.Parse(strDateTime);
return dt.ToString();
}
catch
{
return null;
}
} private string GetEncodedValueString(string SourceString, string Key, bool SplitBySemicolon)
{
int j;
string strValue;
string strSource = SourceString.ToLower();
string strReturn = "";
j = strSource.IndexOf(Key.ToLower());
if (j != -)
{
j += Key.Length;
int kk = strSource.IndexOf("\n", j);
strValue = SourceString.Substring(j, kk - j).TrimEnd();
do
{
if (strValue.IndexOf("=?") != -)
{
if (SplitBySemicolon == true)
{
strReturn += ConvertStringEncodingFromBase64(strValue) + "; ";
}
else
{
strReturn += ConvertStringEncodingFromBase64(strValue);
}
}
else
{
strReturn += strValue;
}
j += strValue.Length + ;
if (strSource.IndexOf("\r\n", j) == -)
{
break;
}
else
{
strValue = SourceString.Substring(j, strSource.IndexOf("\r\n", j) - j).TrimEnd();
}
}
while (strValue.StartsWith(" ") || strValue.StartsWith("\t"));
}
else
{
strReturn = "";
}
return strReturn;
} private string GetValueString(string SourceString, string Key, bool ContainsQuotationMarks, bool ContainsSemicolon)
{
int j;
string strReturn;
string strSource = SourceString.ToLower();
j = strSource.IndexOf(Key.ToLower());
if (j != -)
{
j += Key.Length;
strReturn = SourceString.Substring(j, strSource.IndexOf("\n", j) - j).TrimStart().TrimEnd();
if (ContainsSemicolon == true)
{
if (strReturn.IndexOf(";") != -)
{
strReturn = strReturn.Substring(, strReturn.IndexOf(";"));
}
}
if (ContainsQuotationMarks == true)
{
int i = strReturn.IndexOf("\"");
int k;
if (i != -)
{
k = strReturn.IndexOf("\"", i + );
if (k != -)
{
strReturn = strReturn.Substring(i + , k - i - );
}
else
{
strReturn = strReturn.Substring(i + );
}
}
}
return strReturn;
}
else
{
return "";
}
} private string ConvertStringEncodingFromBase64(string SourceString)
{
try
{
if (SourceString.IndexOf("=?") == -)
{
return SourceString;
}
else
{
int i = SourceString.IndexOf("?");
int j = SourceString.IndexOf("?", i + );
int k = SourceString.IndexOf("?", j + );
char chrTransEnc = SourceString[j + ];
switch (chrTransEnc)
{
case 'B':
return ConvertStringEncodingFromBase64Ex(SourceString.Substring(k + , SourceString.IndexOf("?", k + ) - k - ), SourceString.Substring(i + , j - i - ));
default:
throw new Exception("unhandled content transfer encoding");
}
}
}
catch
{
return "";
}
} /// <summary>
/// 把Base64编码转换成字符串
/// </summary>
/// <param name="SourceString"></param>
/// <param name="Charset"></param>
/// <returns></returns>
private string ConvertStringEncodingFromBase64Ex(string SourceString, string Charset)
{
try
{
Encoding enc;
if (Charset == "")
enc = Encoding.Default;
else
enc = Encoding.GetEncoding(Charset); return enc.GetString(Convert.FromBase64String(SourceString));
}
catch
{
return "";
}
} /// <summary>
/// 把字符串转换成Base64Ex编码
/// </summary>
/// <param name="SourceString"></param>
/// <param name="Charset"></param>
/// <param name="AutoWordWrap"></param>
/// <returns></returns>
private string ConvertStringEncodingToBase64Ex(string SourceString, string Charset, bool AutoWordWrap)
{
Encoding enc = Encoding.GetEncoding(Charset);
byte[] buffer = enc.GetBytes(SourceString);
string strContent = Convert.ToBase64String(buffer);
StringBuilder strTemp = new StringBuilder();
int ii = ;
for (int i = ; i <= strContent.Length / - ; i++)
{
strTemp.Append(strContent.Substring( * i, ) + "\r\n");
ii++;
}
strTemp.Append(strContent.Substring( * (ii)));
strContent = strTemp.ToString(); return strContent;
} private string ConvertStringEncoding(string SourceString, string Charset)
{
try
{
Encoding enc;
if (Charset == "8bit" || Charset == "")
{
enc = Encoding.Default;
}
else
{
enc = Encoding.GetEncoding(Charset);
}
return enc.GetString(Encoding.ASCII.GetBytes(SourceString));
}
catch
{
return Encoding.Default.GetString(Encoding.ASCII.GetBytes(SourceString));
}
} //单击删除信件按钮触发的事件
private void buttonDelete_Click(object sender, EventArgs e)
{
string parameter = listBoxOperation.SelectedItem.ToString();
parameter = parameter.Substring(, parameter.IndexOf("封") - );
SendToServer("DELE " + parameter);
string str = GetResponse();
if (CheckResponse(str) == false) return;
richTextBoxOriginalMail.Clear();
int j = listBoxOperation.SelectedIndex;
listBoxOperation.Items.Remove(listBoxOperation.Items[j].ToString());
MessageBox.Show("删除成功");
}
}
}

C#开发邮件收发(同步)的更多相关文章

  1. 用SugarORM快速开发需要同步和保存大量数据的Android互联网客户端

    最近开发的一个项目主要有两个特点,这两点也是在项目开发前需要着重去规划解决方案的: 需要和Rest服务端请求大量的数据 同时这些数据本地也要保存到sqlite数据库 对于第一点,目前的Volley.G ...

  2. Linux驱动开发5——同步机制

    上一章讲到了并发,指的是多个进程同时存取临界区资源的处理机制.这一章讲的同步机制,讲的是多个进程之间协同工作的处理机制,如临界区数据还没有准备好,A进程负责准备数据,B进程等待A进程完成之后读取数据. ...

  3. iOS开发线程同步技术-锁

    概览 1,什么是锁(临界区)? 2,常用的锁有哪些? 3,相关链接 什么是锁(临界区) 临界区:指的是一块对公共资源进行访问的代码,并非一种机制或是算法. 常用的锁有哪些? 互斥锁:是一种用于多线程编 ...

  4. C#多线程开发-线程同步 02

    上一篇文章主要带领大家认识了线程,也了解到了线程的基本用法和状态,接下来就让我们一起学习下什么是线程同步. 线程中异常的处理 在线程中始终使用try/catch代码块是非常重要的,因为不可能在线程代码 ...

  5. java开发常用jar包介绍(转载)

    jta.jar 标准JTA API必要 commons-collections.jar 集合类 必要 antlr.jar  ANother Tool for Language Recognition ...

  6. laravel下的团队开发

    当你的团队在开发一个大型应用时,该应用的不同部分可能以不同的速度前进.比如,设想下面的场景:一个开发热源被分配 数据层 的backend工作,而另外一个开发人员做front-end和web/contr ...

  7. ios程序开发杂记

    ios程序开发杂记 一.程序构建 与一般的程序构建无太大区别,都是源文件编译链接这一套,通常是在mac上做交叉编译,也就是利用xcode里带的ios编译工具集去生成arm架构的ios程序(或是x86的 ...

  8. .NET软件开发与常用工具清单

    [工欲善其事,必先利其器]软件开发的第一步就是选择高效.智能的工具. 下面列出的工具软件能辅助提高工作效率.  开发类工具 微软.Net平台下的集成开发环境:Visual Studio. Visual ...

  9. ACE框架 同步原语设计

    ACE框架常用的同步机制设计成统一的原语接口.同步原语使用系统平台(操作系统,多线程库)提供的同步原语,并为系统平台不提供的同步原语提供模拟实现.ACE框架使用了外观模式和适配器分两层,将同步原语统一 ...

随机推荐

  1. centos 6.5 搭建zookeeper集群

    为什么使用Zookeeper? 大部分分布式应用需要一个主控.协调器或控制器来管理物理分布的子进程(如资源.任务分配等)目前,大部分应用需要开发私有的协调程序,缺乏一个通用的机制协调程序的反复编写浪费 ...

  2. 跟我学Spring Boot(二)Hello World

    1.打开DemoApplication添加如下代码 package com.example; import org.springframework.boot.SpringApplication; im ...

  3. Angular学习笔记:Angular CLI

    定义 Angular CLI:The Angular CLI is a command line interface tool that can create a project, add files ...

  4. 【转】再讲IQueryable<T>,揭开表达式树的神秘面纱

    [转]再讲IQueryable<T>,揭开表达式树的神秘面纱 接上篇<先说IEnumerable,我们每天用的foreach你真的懂它吗?> 最近园子里定制自己的orm那是一个 ...

  5. JavaScript基础数据类型

    一.数值 1.JavaScript不区分整型和浮点型,就只有一种数字类型 2.还有一种NaN,表示不是一个数字(Not a Number) eg: parseInt("ABC")  ...

  6. Our Future

    The world is betting on how to win the football game: But I'm betting on how to win your heart: Mayb ...

  7. 2018.11.07 bzoj1965: [Ahoi2005]SHUFFLE 洗牌(快速幂+exgcd)

    传送门 发现自己的程序跑得好慢啊233. 管他的反正AC了 先手玩样例找了一波规律发现题目要求的就是a∗2m≡l(modn+1)a*2^m\equiv l \pmod {n+1}a∗2m≡l(modn ...

  8. 牛客训练四:Applese 走方格(细节)

    题目链接:传送门 思路:主要是n=1,m=2或者n=2,m=1时,不是-1. #include<iostream> #include<cstdio> #include<c ...

  9. 关于上级机构的冲突性测试bug修复

    描述: 1.上级机构可以为空. 2.机构添加时,选择了上级机构,在未提交前,另一用户将该机构删除,然后前一用户再提交表单,提示会保存成功,本操作应该保存失败. 思路:在上级机构不为空时,保存前进行查询 ...

  10. openstack网络基本概念(转)

    OpenStack的Neutron能够管理OpenStack环境中的虚拟 网络基础设施(VNI).和物理网络基础设施(PNI). OpenStack的Neutron同意租户创建虚拟网络拓扑结构.包括的 ...