在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例桌面应用界面/GUI → C#利用邮箱发送邮件和利用邮箱接收软件更新包源代码

C#利用邮箱发送邮件和利用邮箱接收软件更新包源代码

桌面应用界面/GUI

下载此实例
  • 开发语言:C#
  • 实例大小:1.70M
  • 下载次数:5
  • 浏览次数:81
  • 发布时间:2024-11-14
  • 实例类别:桌面应用界面/GUI
  • 发 布 人:不忘初
  • 文件格式:.rar
  • 所需积分:1

实例介绍

【实例简介】

C#利用邮箱发送邮件和利用邮箱接收软件更新包源代码

【实例截图】

from clipboard

【核心代码】

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;
using OpenPop.Mime;
using OpenPop.Mime.Header;
using OpenPop.Pop3;
using OpenPop.Pop3.Exceptions;
using OpenPop.Common.Logging;
using Message = OpenPop.Mime.Message;
//
using System.ComponentModel;
using System.Drawing;
using System.Net.Sockets;
using System.Collections;
using System.Net;
//using System.Web.Mail;
using System.Net.Mail;
using System.Net.Mime;
//
using System.Text.RegularExpressions;//判断文本
using System.Diagnostics;//
namespace OpenPop.TestApplication
{
/// <summary>
/// This class is a form which makes it possible to download all messages
/// from a pop3 mailbox in a simply way.
/// </summary>
public class TestForm : Form
{
private readonly Dictionary<int, Message> messages = new Dictionary<int, Message>();
        private readonly Pop3Client pop3Client;
private ContextMenu contextMenuMessages;
        private DataGrid gridHeaders;
        private Label labelAttachments;
        private TreeView listAttachments;
private MenuItem menuDeleteMessage;
        private MenuItem menuViewSource;
        private SaveFileDialog saveFile;
        private ProgressBar progressBar;

        private MailMessage mail;
        string from = "guesxxxd@126.com";//换成自己的邮箱
        string to = "guestxxx@126.com";//换成自己的邮箱
        private Button submitbutton;
        private TextBox feedbacktextBox;
        private Label popServerlabel;
        private TextBox popServerTextBox;
        private CheckBox useSslCheckBox;
        private TextBox totalMessagesTextBox;
        private Label labelTotalMessages;
        private TextBox passwordTextBox;
        private TextBox loginTextBox;
        private Button connectAndRetrieveButton;
        private TextBox portTextBox;
        private Label labelMessageNumber;
        private TreeView listMessages;
        private Label labelMessageBody;
        private TextBox messageTextBox;
        private Label feedbacklabel;
        private Label Portlabel;
        private Label updatalabel;
private TestForm()
{
//
            // 表单设计器所需的支持
//
InitializeComponent();
//
            //用户定义的东西
//
            // 这就是如何覆盖默认的日志记录器类型
            // 这里我们要记录到一个文件
DefaultLogger.SetLog(new FileLogger());
            // 启用文件日志记录,并包含详细信息
FileLogger.Enabled = true;
FileLogger.Verbose = true;
pop3Client = new Pop3Client();
            // 这只是为了更快的调试目的
            // 我们将尝试从文件中加载主机名、端口、ssl、用户名和密码的默认值
string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string file = Path.Combine(myDocs, "OpenPopLogin.txt");
if (File.Exists(file))
{
using (StreamReader reader = new StreamReader(File.OpenRead(file)))
{
                    // 这描述了OpenPOPLogin的方式。txt文件应该是这样的
                    popServerTextBox.Text = reader.ReadLine(); // Hostname主机名
                    portTextBox.Text = reader.ReadLine(); // Port端口
                    useSslCheckBox.Checked = bool.Parse(reader.ReadLine() ?? "true"); // 是否使用SSL
                    loginTextBox.Text = reader.ReadLine(); // Username用户名
                    passwordTextBox.Text = reader.ReadLine(); // Password密码
}
}
}

#region Windows Form Designer generated code
/// <summary>
        ///   需要设计支持的方法——不要修改
        ///   该方法的内容与代码编辑器。
/// </summary>
private void InitializeComponent()
{
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TestForm));
            this.gridHeaders = new System.Windows.Forms.DataGrid();
            this.progressBar = new System.Windows.Forms.ProgressBar();
            this.contextMenuMessages = new System.Windows.Forms.ContextMenu();
            this.menuDeleteMessage = new System.Windows.Forms.MenuItem();
            this.menuViewSource = new System.Windows.Forms.MenuItem();
            this.listAttachments = new System.Windows.Forms.TreeView();
            this.labelAttachments = new System.Windows.Forms.Label();
            this.saveFile = new System.Windows.Forms.SaveFileDialog();
            this.useSslCheckBox = new System.Windows.Forms.CheckBox();
            this.totalMessagesTextBox = new System.Windows.Forms.TextBox();
            this.labelTotalMessages = new System.Windows.Forms.Label();
            this.passwordTextBox = new System.Windows.Forms.TextBox();
            this.portTextBox = new System.Windows.Forms.TextBox();
            this.loginTextBox = new System.Windows.Forms.TextBox();
            this.popServerTextBox = new System.Windows.Forms.TextBox();
            this.popServerlabel = new System.Windows.Forms.Label();
            this.connectAndRetrieveButton = new System.Windows.Forms.Button();
            this.feedbacktextBox = new System.Windows.Forms.TextBox();
            this.submitbutton = new System.Windows.Forms.Button();
            this.labelMessageNumber = new System.Windows.Forms.Label();
            this.listMessages = new System.Windows.Forms.TreeView();
            this.labelMessageBody = new System.Windows.Forms.Label();
            this.messageTextBox = new System.Windows.Forms.TextBox();
            this.feedbacklabel = new System.Windows.Forms.Label();
            this.Portlabel = new System.Windows.Forms.Label();
            this.updatalabel = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.gridHeaders)).BeginInit();
            this.SuspendLayout();
            // 
            // gridHeaders
            // 
            this.gridHeaders.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.gridHeaders.CaptionText = "属性:";
            this.gridHeaders.DataMember = "";
            this.gridHeaders.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.gridHeaders.Location = new System.Drawing.Point(150, 660);
            this.gridHeaders.Name = "gridHeaders";
            this.gridHeaders.PreferredColumnWidth = 400;
            this.gridHeaders.ReadOnly = true;
            this.gridHeaders.Size = new System.Drawing.Size(120, 154);
            this.gridHeaders.TabIndex = 3;
            this.gridHeaders.Navigate = new System.Windows.Forms.NavigateEventHandler(this.gridHeaders_Navigate);
            // 
            // progressBar
            // 
            this.progressBar.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.progressBar.Location = new System.Drawing.Point(12, 643);
            this.progressBar.Name = "progressBar";
            this.progressBar.Size = new System.Drawing.Size(452, 13);
            this.progressBar.TabIndex = 10;
            // 
            // contextMenuMessages
            // 
            this.contextMenuMessages.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuDeleteMessage,
            this.menuViewSource});
            this.contextMenuMessages.Popup = new System.EventHandler(this.contextMenuMessages_Popup);
            // 
            // menuDeleteMessage
            // 
            this.menuDeleteMessage.Index = 0;
            this.menuDeleteMessage.Text = "删除邮件(Delete Mail)";
            this.menuDeleteMessage.Click = new System.EventHandler(this.MenuDeleteMessageClick);
            // 
            // menuViewSource
            // 
            this.menuViewSource.Index = 1;
            this.menuViewSource.Text = "查看源代码(View source)";
            this.menuViewSource.Click = new System.EventHandler(this.MenuViewSourceClick);
            // 
            // listAttachments
            // 
            this.listAttachments.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.listAttachments.Location = new System.Drawing.Point(14, 679);
            this.listAttachments.Name = "listAttachments";
            this.listAttachments.ShowLines = false;
            this.listAttachments.ShowRootLines = false;
            this.listAttachments.Size = new System.Drawing.Size(120, 135);
            this.listAttachments.TabIndex = 10;
            this.listAttachments.AfterSelect = new System.Windows.Forms.TreeViewEventHandler(this.ListAttachmentsAttachmentSelected);
            // 
            // labelAttachments
            // 
            this.labelAttachments.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.labelAttachments.BackColor = System.Drawing.SystemColors.ActiveCaption;
            this.labelAttachments.Location = new System.Drawing.Point(14, 661);
            this.labelAttachments.Name = "labelAttachments";
            this.labelAttachments.Size = new System.Drawing.Size(120, 17);
            this.labelAttachments.TabIndex = 3;
            this.labelAttachments.Text = "附件Attachments:";
            this.labelAttachments.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // saveFile
            // 
            this.saveFile.Title = "Save Attachment";
            // 
            // useSslCheckBox
            // 
            this.useSslCheckBox.AutoSize = true;
            this.useSslCheckBox.BackColor = System.Drawing.SystemColors.ActiveCaption;
            this.useSslCheckBox.Checked = true;
            this.useSslCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
            this.useSslCheckBox.Location = new System.Drawing.Point(670, 5);
            this.useSslCheckBox.Name = "useSslCheckBox";
            this.useSslCheckBox.Size = new System.Drawing.Size(66, 16);
            this.useSslCheckBox.TabIndex = 4;
            this.useSslCheckBox.Text = "Use SSL";
            this.useSslCheckBox.UseVisualStyleBackColor = false;
            // 
            // totalMessagesTextBox
            // 
            this.totalMessagesTextBox.Location = new System.Drawing.Point(568, 4);
            this.totalMessagesTextBox.Name = "totalMessagesTextBox";
            this.totalMessagesTextBox.Size = new System.Drawing.Size(96, 21);
            this.totalMessagesTextBox.TabIndex = 7;
            // 
            // labelTotalMessages
            // 
            this.labelTotalMessages.BackColor = System.Drawing.SystemColors.ActiveCaption;
            this.labelTotalMessages.Location = new System.Drawing.Point(496, 5);
            this.labelTotalMessages.Name = "labelTotalMessages";
            this.labelTotalMessages.Size = new System.Drawing.Size(66, 13);
            this.labelTotalMessages.TabIndex = 9;
            this.labelTotalMessages.Text = "邮件总量:";
            this.labelTotalMessages.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // passwordTextBox
            // 
            this.passwordTextBox.Location = new System.Drawing.Point(382, 4);
            this.passwordTextBox.Name = "passwordTextBox";
            this.passwordTextBox.PasswordChar = '*';
            this.passwordTextBox.Size = new System.Drawing.Size(108, 21);
            this.passwordTextBox.TabIndex = 2;
            // 
            // portTextBox
            // 
            this.portTextBox.Location = new System.Drawing.Point(276, 4);
            this.portTextBox.Name = "portTextBox";
            this.portTextBox.Size = new System.Drawing.Size(32, 21);
            this.portTextBox.TabIndex = 3;
            this.portTextBox.Text = "110";
            // 
            // loginTextBox
            // 
            this.loginTextBox.Location = new System.Drawing.Point(314, 4);
            this.loginTextBox.Name = "loginTextBox";
            this.loginTextBox.Size = new System.Drawing.Size(62, 21);
            this.loginTextBox.TabIndex = 1;
            // 
            // popServerTextBox
            // 
            this.popServerTextBox.Location = new System.Drawing.Point(111, 4);
            this.popServerTextBox.Name = "popServerTextBox";
            this.popServerTextBox.Size = new System.Drawing.Size(100, 21);
            this.popServerTextBox.TabIndex = 3;
            // 
            // popServerlabel
            // 
            this.popServerlabel.AutoSize = true;
            this.popServerlabel.BackColor = System.Drawing.SystemColors.ActiveCaption;
            this.popServerlabel.Location = new System.Drawing.Point(10, 5);
            this.popServerlabel.Name = "popServerlabel";
            this.popServerlabel.Size = new System.Drawing.Size(95, 12);
            this.popServerlabel.TabIndex = 10;
            this.popServerlabel.Text = "服务器popServer";
            this.popServerlabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // connectAndRetrieveButton
            // 
            this.connectAndRetrieveButton.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("connectAndRetrieveButton.BackgroundImage")));
            this.connectAndRetrieveButton.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.connectAndRetrieveButton.Font = new System.Drawing.Font("宋体", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.connectAndRetrieveButton.ForeColor = System.Drawing.SystemColors.MenuHighlight;
            this.connectAndRetrieveButton.Location = new System.Drawing.Point(14, 67);
            this.connectAndRetrieveButton.Name = "connectAndRetrieveButton";
            this.connectAndRetrieveButton.Size = new System.Drawing.Size(256, 90);
            this.connectAndRetrieveButton.TabIndex = 5;
            this.connectAndRetrieveButton.Text = "打开出租屋无人智能管理系统";
            this.connectAndRetrieveButton.Click = new System.EventHandler(this.ConnectAndRetrieveButtonClick);
            // 
            // feedbacktextBox
            // 
            this.feedbacktextBox.Location = new System.Drawing.Point(12, 251);
            this.feedbacktextBox.Multiline = true;
            this.feedbacktextBox.Name = "feedbacktextBox";
            this.feedbacktextBox.Size = new System.Drawing.Size(452, 90);
            this.feedbacktextBox.TabIndex = 4;
            // 
            // submitbutton
            // 
            this.submitbutton.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("submitbutton.BackgroundImage")));
            this.submitbutton.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.submitbutton.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.submitbutton.ForeColor = System.Drawing.SystemColors.Highlight;
            this.submitbutton.Location = new System.Drawing.Point(14, 347);
            this.submitbutton.Name = "submitbutton";
            this.submitbutton.Size = new System.Drawing.Size(91, 43);
            this.submitbutton.TabIndex = 6;
            this.submitbutton.Text = "提交";
            this.submitbutton.UseVisualStyleBackColor = true;
            this.submitbutton.Click = new System.EventHandler(this.submitbutton_Click);
            // 
            // labelMessageNumber
            // 
            this.labelMessageNumber.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.labelMessageNumber.BackColor = System.Drawing.SystemColors.ActiveCaption;
            this.labelMessageNumber.Location = new System.Drawing.Point(14, 437);
            this.labelMessageNumber.Name = "labelMessageNumber";
            this.labelMessageNumber.Size = new System.Drawing.Size(159, 17);
            this.labelMessageNumber.TabIndex = 2;
            this.labelMessageNumber.Text = "邮件主题:";
            this.labelMessageNumber.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // listMessages
            // 
            this.listMessages.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.listMessages.ContextMenu = this.contextMenuMessages;
            this.listMessages.Location = new System.Drawing.Point(12, 455);
            this.listMessages.Name = "listMessages";
            this.listMessages.Size = new System.Drawing.Size(452, 88);
            this.listMessages.TabIndex = 9;
            this.listMessages.AfterSelect = new System.Windows.Forms.TreeViewEventHandler(this.listMessages_AfterSelect);
            // 
            // labelMessageBody
            // 
            this.labelMessageBody.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.labelMessageBody.BackColor = System.Drawing.SystemColors.ActiveCaption;
            this.labelMessageBody.Location = new System.Drawing.Point(12, 544);
            this.labelMessageBody.Name = "labelMessageBody";
            this.labelMessageBody.Size = new System.Drawing.Size(163, 17);
            this.labelMessageBody.TabIndex = 10;
            this.labelMessageBody.Text = "查看邮件反馈内容:";
            this.labelMessageBody.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // messageTextBox
            // 
            this.messageTextBox.Anchor = System.Windows.Forms.AnchorStyles.Left;
            this.messageTextBox.Location = new System.Drawing.Point(12, 562);
            this.messageTextBox.MaxLength = 999999999;
            this.messageTextBox.Multiline = true;
            this.messageTextBox.Name = "messageTextBox";
            this.messageTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.messageTextBox.Size = new System.Drawing.Size(452, 79);
            this.messageTextBox.TabIndex = 11;
            this.messageTextBox.TextChanged = new System.EventHandler(this.messageTextBox_TextChanged);
            // 
            // feedbacklabel
            // 
            this.feedbacklabel.AutoSize = true;
            this.feedbacklabel.BackColor = System.Drawing.SystemColors.ActiveCaption;
            this.feedbacklabel.Location = new System.Drawing.Point(14, 234);
            this.feedbacklabel.Name = "feedbacklabel";
            this.feedbacklabel.Size = new System.Drawing.Size(89, 12);
            this.feedbacklabel.TabIndex = 12;
            this.feedbacklabel.Text = "提出改进意见:";
            // 
            // Portlabel
            // 
            this.Portlabel.AutoSize = true;
            this.Portlabel.BackColor = System.Drawing.SystemColors.ActiveCaption;
            this.Portlabel.Location = new System.Drawing.Point(217, 5);
            this.Portlabel.Name = "Portlabel";
            this.Portlabel.Size = new System.Drawing.Size(53, 12);
            this.Portlabel.TabIndex = 13;
            this.Portlabel.Text = "端口Port";
            this.Portlabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // updatalabel
            // 
            this.updatalabel.AutoSize = true;
            this.updatalabel.Font = new System.Drawing.Font("宋体", 27.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.updatalabel.ForeColor = System.Drawing.Color.Red;
            this.updatalabel.Location = new System.Drawing.Point(498, 158);
            this.updatalabel.Name = "updatalabel";
            this.updatalabel.Size = new System.Drawing.Size(0, 37);
            this.updatalabel.TabIndex = 14;
            // 
            // TestForm
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
            this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
            this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.ClientSize = new System.Drawing.Size(845, 882);
            this.Controls.Add(this.updatalabel);
            this.Controls.Add(this.Portlabel);
            this.Controls.Add(this.feedbacklabel);
            this.Controls.Add(this.useSslCheckBox);
            this.Controls.Add(this.totalMessagesTextBox);
            this.Controls.Add(this.labelTotalMessages);
            this.Controls.Add(this.popServerTextBox);
            this.Controls.Add(this.passwordTextBox);
            this.Controls.Add(this.popServerlabel);
            this.Controls.Add(this.portTextBox);
            this.Controls.Add(this.feedbacktextBox);
            this.Controls.Add(this.submitbutton);
            this.Controls.Add(this.loginTextBox);
            this.Controls.Add(this.messageTextBox);
            this.Controls.Add(this.listAttachments);
            this.Controls.Add(this.labelMessageBody);
            this.Controls.Add(this.gridHeaders);
            this.Controls.Add(this.listMessages);
            this.Controls.Add(this.connectAndRetrieveButton);
            this.Controls.Add(this.labelMessageNumber);
            this.Controls.Add(this.progressBar);
            this.Controls.Add(this.labelAttachments);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "TestForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "启动出租屋无人智能管理系统";
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            this.Load = new System.EventHandler(this.TestForm_Load);
            ((System.ComponentModel.ISupportInitialize)(this.gridHeaders)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

}
#endregion

/// <summary>
///   The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.Run(new TestForm());
}

private void ReceiveMails()
        {
            updatalabel.Text = "";
// Disable buttons while working
connectAndRetrieveButton.Enabled = false;
//uidlButton.Enabled = false;
progressBar.Value = 0;
try
            {
                DialogResult b = MessageBox.Show("是否下载更新包?可能要一些时间,如果不更新可能会不能使用,建议下载。", "操作提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (b == DialogResult.Yes)
                {
                    updatalabel.Text = "检测是否要更新,时间受网速影响,请稍候......";
                    if (pop3Client.Connected)
                        pop3Client.Disconnect();
                    pop3Client.Connect(popServerTextBox.Text, int.Parse(portTextBox.Text), useSslCheckBox.Checked);
                    pop3Client.Authenticate(loginTextBox.Text, passwordTextBox.Text);
                    int count = pop3Client.GetMessageCount();//读取邮件总数
                    totalMessagesTextBox.Text = count.ToString();
                    messageTextBox.Text = "";
                    messages.Clear();
                    listMessages.Nodes.Clear();//邮件列表
                    listAttachments.Nodes.Clear();//附件列表
                    int success = 0;
                    int fail = 0;
                    for (int i = count; i >= 1; i -= 1)
                    //for (int i = 0; i <= count; i = 1)
                    {
                        // 当我们工作时,检查表格是否关闭。如果是这样,中止
                        if (IsDisposed)
                            return;
                        // 在获取电子邮件时刷新表单
                        // 这将修复“应用程序没有响应”的问题
                        Application.DoEvents();
                        try
                        {
                            Message message = pop3Client.GetMessage(i);
                            // 将消息从消息号添加到消息中
                            messages.Add(i, message);
                            // 创建模仿消息层次结构的树节点树
                            TreeNode node = new TreeNodeBuilder().VisitMessage(message);
                            // 将标记属性设置为消息号
                            // 我们可以稍后再使用它来查找消息
                            node.Tag = i;
                            // 在消息列表中显示已构建的节点
                            listMessages.Nodes.Add(node);
                            success ;
                            //
                            // 清除附件清单,从任何以前显示附件
                            listAttachments.Nodes.Clear();
                            // 建立附件列表
                            List<MessagePart> attachments = message.FindAllAttachments();
                            foreach (MessagePart attachment in attachments)
                            {
                                // 将附件添加到附件列表中
                                TreeNode addedNode = listAttachments.Nodes.Add((attachment.FileName));
                                // 在标记属性中保留对附件的引用
                                addedNode.Tag = attachment;
                                //MessageBox.Show(attachment.FileName);
                                string BakName = attachment.FileName;
                                string NewVersion = attachment.FileName;
                                FileInfo Verfile = new FileInfo(System.Windows.Forms.Application.StartupPath @"\Version.txt");
                                if (!Verfile.Exists)
                                {
                                    File.WriteAllText(System.Windows.Forms.Application.StartupPath @"\Version.txt", "0");
                                }
                                string Version = File.ReadAllText(System.Windows.Forms.Application.StartupPath @"\Version.txt");
                                for (int ni = 0; ni < attachment.FileName.Length; ni )
                                {
                                    Regex rx = new Regex("^[\u4e00-\u9fa5]$");
                                    if (rx.IsMatch(attachment.FileName.Substring(ni, 1)))
                                    {
                                        // MessageBox.Show("是中文" allstr.Substring(ci, 1));
                                    }
                                    else
                                    {
                                        Regex rex = new Regex("[0-9_] ");
                                        Match ma = rex.Match(attachment.FileName.Substring(ni, 1));
                                        if (ma.Success)
                                        {
                                            BakName = BakName.Replace(attachment.FileName.Substring(ni, 1), "");//改变字符为%
                                            //  MessageBox.Show("有数字" allstr.Substring(ci, 1));
                                        }
                                        else
                                        {
                                            NewVersion = NewVersion.Replace(attachment.FileName.Substring(ni, 1), "");//改变字符为%
                                            //   MessageBox.Show("没有数字");//其他字符
                                        }
                                    }
                                }
                               MessageBox.Show("更新包名:" BakName ":新版本:" NewVersion "旧版本:" Version);
                                if (BakName == "Rentalhousing.bak" && Convert.ToInt32(NewVersion) > Convert.ToInt32(Version))//如果得到的文件名符合条件,同时获取的版本大于当前版本。
                                {
                                    updatalabel.Text = "系统正在下载更新包,请稍候......";
                                    // 现在我们要保存附件
                                    FileInfo file = new FileInfo(System.Windows.Forms.Application.StartupPath @"\Rentalhousing.exe");
                                    // Check if the file already exists检查文件是否已经存在
                                    if (file.Exists)
                                    {
                                        file.Delete();
                                    }
                                    //让我们尝试保存到文件中
                                    try
                                    {
                                        attachment.Save(file);
                                        File.WriteAllText(System.Windows.Forms.Application.StartupPath @"\Version.txt", NewVersion);
                                        MessageBox.Show(this, "系统更新成功!" file);
                                        updatalabel.Text = "系统更新成功!";
                                    }
                                    catch (Exception e)
                                    {
                                        updatalabel.Text = "下载更新包失败!";
                                        // MessageBox.Show(this, "附件保存失败。异常信息:(Attachment saving failed. Exception message):" e.Message);
                                    }
                                }
                                else
                                {
                                    updatalabel.Text = "系统已是最新,不需更新。";
                                }
                            }
                            //只有在消息中有附件时才显示附件面板
                            bool hadAttachments = attachments.Count > 0;
                            //attachmentPanel.Visible = hadAttachments;
                        }
                        catch (Exception e)
                        {
                            DefaultLogger.Log.LogError(
                                "TestForm: Message fetching failed: " e.Message "\r\n"
                                "Stack trace:\r\n"
                                e.StackTrace);
                            fail ;
                        }
                        progressBar.Value = (int)(((double)(count - i) / count) * 100);
                    }
                    if (fail > 0)
                    {
                        MessageBox.Show(this,
                                        "因为有些邮件没有正确解析(抛出异常)Since some of the emails were not parsed correctly (exceptions were thrown)\r\n"
                                        "请考虑将您的日志文件发送给开发人员进行修复。please consider sending your log file to the developer for fixing.\r\n"
                                        "如果你能包含任何额外的信息,请这样做。If you are able to include any extra information, please do so.",
                                        "帮助改善OpenPop !Help improve OpenPop!");
                    }
                    //updatalabel.Text = "";
                }
               // MessageBox.Show(this, "邮件收到!\n成功Mail received!\nSuccesses: " success "失败的\nFailed: " fail, "完成信息获取Message fetching done");
                if (File.Exists(System.Windows.Forms.Application.StartupPath @"\Rentalhousing.exe"))//检测文件是否存在
                {
                    Process.Start(System.Windows.Forms.Application.StartupPath @"\Rentalhousing.exe", "");//打开系统
                }
} catch (InvalidLoginException)
{
                MessageBox.Show(this, "服务器不接受用户凭证!The server did not accept the user credentials!", "POP3 Server Authentication");
} catch (PopServerNotFoundException)
{
                MessageBox.Show(this, "服务器无法找到The server could not be found", "POP3 Retrieval");
} catch(PopServerLockedException)
{
                MessageBox.Show(this, "邮箱是锁着的。它可能在使用中或在维护中。你联系其他地方吗?The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked");
} catch (LoginDelayException)
{
                MessageBox.Show(this, "不允许登录。服务器执行logins之间的延迟。你最近有联系吗?Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay");
} catch (Exception e)
{
                MessageBox.Show(this, "错误发生检索邮件。Error occurred retrieving mail. " e.Message, "POP3 Retrieval");
} finally
{
                // 再次启用按钮
connectAndRetrieveButton.Enabled = true;
//uidlButton.Enabled = true;
progressBar.Value = 100;
}
}

private void ConnectAndRetrieveButtonClick(object sender, EventArgs e)
{
ReceiveMails();
}

        //private void ListMessagesMessageSelected(object sender, TreeViewEventArgs e)
        private void listMessages_AfterSelect(object sender, TreeViewEventArgs e)
{
            // 取出所选的消息
Message message = messages[GetMessageNumberFromSelectedNode(listMessages.SelectedNode)];

            // 如果选择的节点包含一个消息部分,我们可以显示内容——显示它们
if (listMessages.SelectedNode.Tag is MessagePart)
{
MessagePart selectedMessagePart = (MessagePart)listMessages.SelectedNode.Tag;
if (selectedMessagePart.IsText)
{
                    // 我们可以显示文本消息部分
messageTextBox.Text = selectedMessagePart.GetBodyAsText();
}
else
{
                    // 我们不能显示非文本消息部分(多部分消息、图像、pdf…)
                    messageTextBox.Text = "<<OpenPop>> 不能显示这部分邮件,这不是文本。Cannot show this part of the email. It is not text <<OpenPop>>";
}
}
else
{
                // 如果所选节点不是子节点,因此没有
                // 在它的标签属性中,我们一般会找到一些内容来显示吗

                // 查找第一个文本/普通版本
MessagePart plainTextPart = message.FindFirstPlainTextVersion();
if (plainTextPart != null)
{
                    // 这个消息有一个文本/普通版本——显示那个
messageTextBox.Text = plainTextPart.GetBodyAsText();
} else
{
                    // 试着找一个身体来展示其他的文本版本
List<MessagePart> textVersions = message.FindAllTextVersions();
if (textVersions.Count >= 1)
messageTextBox.Text = textVersions[0].GetBodyAsText();
else
                        messageTextBox.Text = "<<OpenPop>> 无法在此消息中找到文本版本正文Cannot find a text version body in this message to show <<OpenPop>>";
}
}

            // 清除附件清单,从任何以前显示附件
listAttachments.Nodes.Clear();

            // 建立附件列表
List<MessagePart> attachments = message.FindAllAttachments();
foreach (MessagePart attachment in attachments)
{
                // 将附件添加到附件列表中
TreeNode addedNode = listAttachments.Nodes.Add((attachment.FileName));
                // 在标记属性中保留对附件的引用
addedNode.Tag = attachment;
}

            //只有在消息中有附件时才显示附件面板
bool hadAttachments = attachments.Count > 0;
//attachmentPanel.Visible = hadAttachments;
            // 生成头表
DataSet dataSet = new DataSet();
DataTable table = dataSet.Tables.Add("Headers");
            table.Columns.Add("表头Header");
table.Columns.Add("键值Value");
DataRowCollection rows = table.Rows;
            // 添加所有已知的头
            rows.Add(new object[] { "内容描述Content-Description", message.Headers.ContentDescription });
            rows.Add(new object[] { "内容识别Content-Id", message.Headers.ContentId });
            foreach (string keyword in message.Headers.Keywords) rows.Add(new object[] { "关键字Keyword", keyword });
foreach (RfcMailAddress dispositionNotificationTo in message.Headers.DispositionNotificationTo) rows.Add(new object[] {"送达Disposition-Notification-To", dispositionNotificationTo});
            foreach (Received received in message.Headers.Received) rows.Add(new object[] { "收到Received", received.Raw });
            rows.Add(new object[] { "重要性Importance", message.Headers.Importance });
rows.Add(new object[] {"内容-转移-编码-Content-Transfer-Encoding", message.Headers.ContentTransferEncoding});
foreach (RfcMailAddress cc in message.Headers.Cc) rows.Add(new object[] {"抄送Cc", cc});
foreach (RfcMailAddress bcc in message.Headers.Bcc) rows.Add(new object[] {"密送Bcc", bcc});
foreach (RfcMailAddress to in message.Headers.To) rows.Add(new object[] { "收件邮箱To", to });
            rows.Add(new object[] { "发件邮箱From", message.Headers.From });
            rows.Add(new object[] { "回复Reply-To", message.Headers.ReplyTo });
            foreach (string inReplyTo in message.Headers.InReplyTo) rows.Add(new object[] { "在回复In-Reply-To", inReplyTo });
            foreach (string reference in message.Headers.References) rows.Add(new object[] { "参考文献References", reference });
            rows.Add(new object[] { "发件人Sender", message.Headers.Sender });
            rows.Add(new object[] { "内容类型Content-Type", message.Headers.ContentType });
            rows.Add(new object[] { "附加项Content-Disposition", message.Headers.ContentDisposition });
            rows.Add(new object[] { "日期Date", message.Headers.Date });
            rows.Add(new object[] { "日期Date", message.Headers.DateSent });
            rows.Add(new object[] { "信息地址Message-Id", message.Headers.MessageId });
            rows.Add(new object[] { "版本Mime-Version", message.Headers.MimeVersion });
rows.Add(new object[] {"返回路径Return-Path", message.Headers.ReturnPath});
            rows.Add(new object[] { "主题Subject", message.Headers.Subject });

            // 添加所有未知的头
foreach (string key in message.Headers.UnknownHeaders)
{
string[] values = message.Headers.UnknownHeaders.GetValues(key);
if (values != null)
foreach (string value in values)
{
rows.Add(new object[] {key, value});
}
}

            // 现在将在GUI上显示的头文件设置为刚刚生成的头表
gridHeaders.DataMember = table.TableName;
gridHeaders.DataSource = dataSet;
}

/// <summary>
        /// 查找给定<查看cref = " TreeNode " / >的消息的MessageNumber。
        /// 这个< see cref = " TreeNode " / >的根应该将标记属性设置为int
        /// 指向<查看cref = "消息" / >字典。
/// </summary>
        /// < param name = "节点" > <见cref = " TreeNode " / >查看。不能<看到langword = "零" / > < / param >。
        ///<返回>发现int < /返回>
private static int GetMessageNumberFromSelectedNode(TreeNode node)
{
if (node == null)
throw new ArgumentNullException("node");

            // 检查我们是否在根目录中,查看是否将标签属性设置为int
if(node.Tag is int)
{
return (int) node.Tag;
}

            // 否则我们不是在根结点上,而是向上移动
return GetMessageNumberFromSelectedNode(node.Parent);
}

private void ListAttachmentsAttachmentSelected(object sender, TreeViewEventArgs args)
{
            //获取当前选中的附件部分
MessagePart attachment = (MessagePart)listAttachments.SelectedNode.Tag;
if (attachment != null)
{
saveFile.FileName = attachment.FileName;
DialogResult result = saveFile.ShowDialog();
if (result != DialogResult.OK)
return;
                // 现在我们要保存附件
FileInfo file = new FileInfo(saveFile.FileName);
                // Check if the file already exists检查文件是否已经存在
if(file.Exists)
{
                    // User was asked when he chose the file, if he wanted to overwrite it用户在选择文件时被问到,如果他想要覆盖它
                    // Therefore, when we get to here, it is okay to delete the file因此,当我们到达这里时,删除文件是可以的
file.Delete();
}
                //让我们尝试保存到文件中
try
{
attachment.Save(file);
                    MessageBox.Show(this, "附件保存成功!(Attachment saved successfully!)");
} catch (Exception e)
{
                    MessageBox.Show(this, "附件保存失败。异常信息:(Attachment saving failed. Exception message):" e.Message);
}
}
else
{
                MessageBox.Show(this, "没有附件!(Attachment object was null!)");
}
}

private void MenuDeleteMessageClick(object sender, EventArgs e)
{
if (listMessages.SelectedNode != null)
{
                DialogResult drRet = MessageBox.Show(this, "你要删除这封邮件吗?(Are you sure to delete the email?)", "Delete email", MessageBoxButtons.YesNo);
if (drRet == DialogResult.Yes)
{
                    int messageNumber = GetMessageNumberFromSelectedNode(listMessages.SelectedNode);
pop3Client.DeleteMessage(messageNumber);
                    //listMessages.Nodes[messageNumber].Remove();
                    //drRet = MessageBox.Show(this, "Do you want to receive email again (this will commit your changes)?你想再次收到电子邮件吗?(这将提交你的更改)", "Receive email", MessageBoxButtons.YesNo);
                    //if (drRet == DialogResult.Yes)
                    //MessageBox.Show("" messageNumber);
ReceiveMails();
}
}
}

        //private void UidlButtonClick(object sender, EventArgs e)
        //{
        //    List<string> uids = pop3Client.GetMessageUids();
        //    StringBuilder stringBuilder = new StringBuilder();
        //    stringBuilder.Append("UIDL:");
        //    stringBuilder.Append("\r\n");
        //    foreach (string uid in uids)
        //    {
        //        stringBuilder.Append(uid);
        //        stringBuilder.Append("\r\n");
        //    }
        //    messageTextBox.Text = stringBuilder.ToString();
        //}

private void MenuViewSourceClick(object sender, EventArgs e)
{

if (listMessages.SelectedNode != null)
{
int messageNumber = GetMessageNumberFromSelectedNode(listMessages.SelectedNode);
Message m = messages[messageNumber];
                // 我们不知道完整信息的编码——而各部分的编码可能会有所不同
                // 编码。因此,我们可以选择在原始字节上使用us - ascii编码
                // 获取消息的源代码。任何非ascii编码的字节将会被使用
                //变成问号" ?
ShowSourceForm sourceForm = new ShowSourceForm(Encoding.ASCII.GetString(m.RawMessage));
sourceForm.ShowDialog();
}
}

        private void labelServerAddress_Click(object sender, EventArgs e)
        {

        }

        private void panelTop_Paint(object sender, PaintEventArgs e)
        {

        }

        private void TestForm_Load(object sender, EventArgs e)
        {
            popServerTextBox.Text = "pop.126.com";
            loginTextBox.Text = "guestxxxx";//这里填写您的用户名
            passwordTextBox.Text = "passwordhjhshshshhshs";//这里填写您的客户端密码
            useSslCheckBox.Checked = false;
            labelMessageNumber.Visible = false;//邮件标题显示
            listMessages.Visible = false;//邮件显示
            labelMessageBody.Visible = false;//邮件内容显示
            messageTextBox.Visible = false;//邮件内容标题显示
            progressBar.Visible = false;//进度条显示
            listAttachments.Visible = false;//附件显示
            labelAttachments.Visible = false;//附件标题显示
            gridHeaders.Visible = false;//网格头显示
        }
        protected void SendSuccess(string from, string to)
        {
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
            //message.From = new MailAddress("test@gmail.com", "someone");//必须是提供smtp服务的邮件服务器 
            message.From = new MailAddress(from); //发件
            message.To.Add(new MailAddress(to)); //收件
            message.To.Add(new MailAddress("guestXXX@163.com")); //收件邮箱
            //message.To.Add(new MailAddress("guestXXX@qq.com"));//收件邮箱 
            //message.CC.Add(new MailAddress("guestxxx@126.com"));//抄送
            //message.Bcc.Add(new MailAddress("guestxxx@126.com"));//密送
            //为 message 添加附件
            if (!Directory.Exists(System.Windows.Forms.Application.StartupPath @"\UpData"))
            {
                Directory.CreateDirectory(System.Windows.Forms.Application.StartupPath @"\UpData");//文件夹创建
            }
            string[] dirs = Directory.GetFiles(System.Windows.Forms.Application.StartupPath @"\UpData");
            foreach (string dir in dirs)
            //foreach (TreeNode treeNode in treeViewFileList.Nodes)
            {
                // MessageBox.Show("" dir "");
                //得到文件名
                string fileName = dir;
                //判断文件是否存在
                if (File.Exists(fileName))
                {
                    //构造一个附件对象
                    Attachment attach = new Attachment(fileName);
                    //得到文件的信息
                    ContentDisposition disposition = attach.ContentDisposition;
                    disposition.CreationDate = System.IO.File.GetCreationTime(fileName);
                    disposition.ModificationDate = System.IO.File.GetLastWriteTime(fileName);
                    disposition.ReadDate = System.IO.File.GetLastAccessTime(fileName);
                    //向邮件添加附件
                    message.Attachments.Add(attach);
                }
                else
                {
                    MessageBox.Show("文件" fileName "未找到!");
                }
            }
            //添加邮件主题和内容
            message.Subject = "主题:" DateTime.Now.ToString() "反馈的内容"; ;
            message.IsBodyHtml = true;
            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.Body = "邮件发送测试内容:" feedbacktextBox.Text;
            message.Priority = System.Net.Mail.MailPriority.High;
            //SmtpClient client = new SmtpClient("smtp.gmail.com", 587); // 587;//Gmail使用的端口
            //163.com: POP3服务器接受地址:pop.163.com(端口:110)SMTP服务器发送地址:smtp.163.com(端口:25)
            SmtpClient client = new SmtpClient("smtp.126.com", 25);
            client.Credentials = new System.Net.NetworkCredential("guestxxx", "password1");//这里是申请的邮箱和密码 
            client.EnableSsl = true; //必须经过ssl加密 
            try
            {
                //
                client.Send(message);
                //Response.Write("邮件已经成功发送到" message.To.ToString() "<br>");
                MessageBox.Show("邮件已经成功发送到:" message.To.ToString());
            }
            catch (Exception ee)
            {
                //Response.Write(ee.Message "<br>" /* ee.InnerException.Message*/ );
                MessageBox.Show(ee.Message "<br>");
            }
        }
        private void submitbutton_Click(object sender, EventArgs e)
        {
            SendSuccess(from, to);
        }
        private void contextMenuMessages_Popup(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
        private void messageTextBox_TextChanged(object sender, EventArgs e)
        {

        }

        private void gridHeaders_Navigate(object sender, NavigateEventArgs ne)
        {

        }


}
}

实例下载地址

C#利用邮箱发送邮件和利用邮箱接收软件更新包源代码

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警