码迷,mamicode.com
首页 > Windows程序 > 详细

[工具-008] C#邮件发送系统

时间:2015-08-10 21:51:27      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:

邮件发送系统很多,但是我这边给大家展示下我最近开发的一款邮件发送系统,有参照网上的一个兄弟的界面,进行了升级,界面如下。

技术分享

从界面上我们可以看到了该邮件系统有如下功能:

1)服务器的设置

2)发件人的设置

3)收件人的设置

4)主题编写

5)附件添加管理

6)日志输出

7)窗口关闭的时候会自动保存服务器,收件人信息。

整体的实现代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using SendEmail.util;
using System.Collections;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;

namespace SendEmail
{
    public partial class Form1 : Form
    {
        #region 常量定义
        // 服务器备份地址
        private const string SERVER_BACK_UP_PATH = "server.txt";
        // 收件人备份地址
        private const string EmailFrom_BACK_UP_PATH = "emailaddress.txt";
        #endregion

        #region 变量定义
        // 服务器存放
        private Dictionary<string, int> serverMap = new Dictionary<string,int>();
        private ArrayList serverList =  new ArrayList();
        // 收件人存放
        private ArrayList emailFroms = new ArrayList();
        #endregion

        #region 构造函数
        public Form1()
        {
            InitializeComponent();
            // 初始化服务器
            initComServer();
            // 初始化收件人
            initGrdEmail();
        }
        #endregion

        #region 服务器地址
        // 初始化设备列表(从txt中读取设备信息)
        private void initComServer()
        {
            // 假如数据文件存在
            if (File.Exists(SERVER_BACK_UP_PATH))
            {
                ArrayList datas = FileUtil.readFile(SERVER_BACK_UP_PATH);
                // 数据存在
                if (datas != null && datas.Count > 0)
                {
                    // 清空数据
                    serverMap.Clear();
                    serverList.Clear();
                    // 遍历
                    foreach (string s in datas)
                    {
                        string[] splitArray = s.Split(‘,‘);
                        // 1.服务器名称 2.端口
                        if (splitArray != null && splitArray.Length == 2)
                        {
                            serverList.Add(splitArray[0]);
                            serverMap.Add(splitArray[0], int.Parse(splitArray[1]));
                        }
                    }
                    bindComServer();
                }
            }
        }

        // 绑定下拉框
        private void bindComServer()
        {
            comServer.Items.Clear();
            comdelServer.Items.Clear();
            foreach (string s in serverList)
            {
                comServer.Items.Add(s);
                comdelServer.Items.Add(s);
            }
            comServer.SelectedIndex = 0;
            comdelServer.SelectedIndex = 0;
        }

        // 添加服务
        private void button1_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.txtServer.Text.Trim()))
            {
                MessageBox.Show("请填写服务器地址!!!", "友情提示");
                return;
            }
            serverList.Add(this.txtServer.Text.Trim());
            serverMap.Add(this.txtServer.Text.Trim(), int.Parse(this.numport.Value+""));
            bindComServer();
            MessageBox.Show("添加成功!!!", "友情提示");
        }

        // 删除服务
        private void button2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要删除服务吗?", "删除前确认", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }
            string delserver = comdelServer.Text.Trim();
            if (serverList.Contains(delserver))
            {
                serverList.Remove(delserver);
                serverMap.Remove(delserver);
            }
            bindComServer();
        }

        // 保存服务列表(保存到txt中)
        private void saveServerCmb()
        {
            ArrayList dataList = new ArrayList();
            if (this.serverMap != null && this.serverMap.Count > 0)
            {
                foreach (string s in this.serverMap.Keys)
                {
                    string appendtext = s + "," + serverMap[s];
                    dataList.Add(appendtext);
                }
                FileUtil.saveFile(SERVER_BACK_UP_PATH, dataList);
            }
        }
        #endregion

        #region 收件邮箱地址
        private void initGrdEmail()
        {
            // 假如数据文件存在
            if (File.Exists(EmailFrom_BACK_UP_PATH))
            {
                ArrayList datas = FileUtil.readFile(EmailFrom_BACK_UP_PATH);
                // 数据存在
                if (datas != null && datas.Count > 0)
                {
                    // 清空数据
                    emailFroms.Clear();
                    // 遍历
                    foreach (string s in datas)
                    {
                        emailFroms.Add(s.Trim());
                        int vRownumber = this.grdEmails.Rows.Add();
                        this.grdEmails.Rows[vRownumber].Cells[0].Value = s.Trim();
                    }
                }
            }
        }

        // 邮箱地址添加到GridView中
        private void btnEmailAdd_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txtEamilTo.Text.Trim()))
            {
                if (this.txtEamilTo.ForeColor == Color.Red)
                {
                    MessageBox.Show("输入的收件箱格式不正确!");
                }
                else
                {
                    emailFroms.Add(this.txtEamilTo.Text.Trim());
                    int vRownumber = this.grdEmails.Rows.Add();
                    this.grdEmails.Rows[vRownumber].Cells[0].Value = this.txtEamilTo.Text.Trim();
                    this.txtEamilTo.Text = string.Empty;
                }
            }
        }

        // 邮箱地址 删除
        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (this.grdEmails.Rows.Count > 0)
            {
                // 只可选中一条,进行删除
                // int vCurrentIndex = this.grdEmails.CurrentRow.Index;
                // this.grdEmails.Rows.RemoveAt(vCurrentIndex);
                // 支持多选删除
                foreach (DataGridViewRow vrow in grdEmails.SelectedRows)
                {
                    int vIndex = vrow.Index;
                    this.grdEmails.Rows.RemoveAt(vIndex);
                    emailFroms.RemoveAt(vIndex);
                }
            }
        }

        // 邮箱地址 清空
        private void btnClear_Click(object sender, EventArgs e)
        {
            this.grdEmails.Rows.Clear();
            emailFroms.Clear();
        }

        // 保存邮箱到txt
        private void saveGrdEmail()
        {
            ArrayList dataList = new ArrayList();
            if (this.emailFroms != null && this.emailFroms.Count > 0)
            {
                foreach (string s in this.emailFroms)
                {
                    dataList.Add(s);
                }
                FileUtil.saveFile(EmailFrom_BACK_UP_PATH, dataList);
            }
        }
        #endregion

        #region 验证邮箱输入是否正确,不正确是,字体显示为红色
        // 验证 发件邮箱是否正确
        private void txtEmailTo_Leave(object sender, EventArgs e)
        {

            if (!string.IsNullOrEmpty(this.txtEamilTo.Text.Trim()))
            {
                bool a = IsEmail(this.txtEamilTo.Text);
                // 如果不为 邮箱,字体变为红色
                if (IsEmail(this.txtEamilTo.Text.Trim()) == false)
                {
                    this.txtEamilTo.ForeColor = Color.Red;
                }
                else
                {
                    this.txtEamilTo.ForeColor = Color.Black;
                }
            }
        }

        private bool IsEmail(string vEmail)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(vEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        // 验证 收件箱邮箱是否正确
        private void txtEamilFrom_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txtEamilFrom.Text.Trim()))
            {
                bool a = IsEmail(this.txtEamilFrom.Text);
                // 如果不为 邮箱,字体变为红色
                if (IsEmail(this.txtEamilFrom.Text.Trim()) == false)
                {
                    this.txtEamilFrom.ForeColor = Color.Red;
                }
                else
                {
                    this.txtEamilFrom.ForeColor = Color.Black;
                }
            }
        }
        #endregion

        #region 参数
        // 保存 附件文件路径
        private ArrayList Files = new ArrayList();
        // 设置SMTP协议
        private SmtpClient vSmtpClient = null;
        // 设置发件人地址,需要密码
        private MailAddress vMailAddressFrom = null;
        // 设置收件人地址,不需要密码
        private MailAddress vMailAddressTo = null;
        // 附件文件流vMailAddressFrom
        private FileStream vFileStream = null;
        private MailMessage vMailMessage = null;
        #endregion

        #region 附件操作(支持多选,可以同时上传多个附件)
        private void btnFileSelect_Click(object sender, EventArgs e)
        {
            OpenFileDialog vOpenSelectFile = new OpenFileDialog();
            vOpenSelectFile.Multiselect = true;
            vOpenSelectFile.Filter = "全部文件|*.*|Excel文件|*.xlsx;*.xls|Csv文件|*.csv";
            vOpenSelectFile.FilterIndex = 2;
            vOpenSelectFile.RestoreDirectory = true;
            if (vOpenSelectFile.ShowDialog() == DialogResult.OK)
            {
                string message = "";
                for (int i = 0; i < vOpenSelectFile.FileNames.Length; i++)
                {
                    if (Check_File(vOpenSelectFile.FileNames[i].ToString(), out message))
                    {
                        Files.Add(vOpenSelectFile.FileNames[i].ToString());
                        int vRownumber = this.grdAttach.Rows.Add();
                        this.grdAttach.Rows[vRownumber].Cells[0].Value = vOpenSelectFile.FileNames[i].ToString();
                    }
                    else
                    {
                        appendLogLn(message);
                    }
                }
            }
        }

        // 附件 清空
        private void btnClearAttach_Click(object sender, EventArgs e)
        {
            this.grdAttach.Rows.Clear();
            Files.Clear();
        }

        // 附件 删除
        private void btnDelattach_Click(object sender, EventArgs e)
        {
            if (this.grdAttach.Rows.Count > 0)
            {
                // 只可选中一条,进行删除
                // int vCurrentIndex = this.grdEmails.CurrentRow.Index;
                // this.grdEmails.Rows.RemoveAt(vCurrentIndex);
                // 支持多选删除
                foreach (DataGridViewRow vrow in grdAttach.SelectedRows)
                {
                    int vIndex = vrow.Index;
                    this.grdAttach.Rows.RemoveAt(vIndex);
                    Files.RemoveAt(vIndex);
                }
            }
        }
        #endregion

        #region 验证页面必填项是否已经完善
        private bool CheckPage()
        {
            if (string.IsNullOrEmpty(this.comServer.Text))
            {
                MessageBox.Show("请输入SMTP服务器名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else if (string.IsNullOrEmpty(this.txtEamilFrom.Text))
            {
                MessageBox.Show("请输入发件人邮箱地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else if (string.IsNullOrEmpty(this.txtformPwd.Text))
            {
                MessageBox.Show("请输入发件人邮箱密码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else if (this.grdEmails.Rows.Count < 1)
            {
                MessageBox.Show("请输入收件人邮箱地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else if (string.IsNullOrEmpty(this.txtEmailtitle.Text))
            {
                MessageBox.Show("请输入邮件标题", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
        }
        #endregion

        #region 邮件发送
        // 设置SMTP服务器信息
        private void SetSmtpClient(string vServerHost)
        {
            vSmtpClient = new SmtpClient();
            // SMTP服务器的名称
            vSmtpClient.Host = vServerHost;
            // 指定端口号
            vSmtpClient.Port = serverMap[vServerHost];
            // 超时时间
            vSmtpClient.Timeout = 0;
        }

        // 验证发件人信息
        private void SetAddressForm(string vMailAddress, string vMailPwd)
        {
            // 创建服务器认证
            NetworkCredential vNetwork = new NetworkCredential(vMailAddress, vMailPwd);
            // 实例化 发件人地址
            vMailAddressFrom = new MailAddress(vMailAddress, "");
            // 指定发件人信息,包括邮箱地址和邮箱密码
            vSmtpClient.Credentials = new NetworkCredential(vMailAddressFrom.Address, vMailPwd);
        }

        // 检测附件大小
        private bool Check_File(string vFilePath, out string vInfo)
        {
            try
            {
                vFileStream = new FileStream(vFilePath, FileMode.Open);
            }
            catch (Exception e)
            {
                vInfo = "文件名为:" + vFilePath + "的文件被占用或者不能打开。";
                return false;
            }
            string vFileName = vFileStream.Name;
            int vSize = Convert.ToInt32(vFileStream.Length / 1024 / 1024);
            vFileStream.Close();
            if (vSize > 15)
            {
                vInfo = "文件名为:" + vFileName + "的文件大小大于15M,不允许上传。";
                return false;
            }
            vInfo = string.Empty;
            return true;
        }

        // 发送
        private void btnSaveTo_Click(object sender, EventArgs e)
        {
            // 必填项验证通过
            if (CheckPage())
            {
                // 初始化Smtp服务器信息
                SetSmtpClient(this.comServer.Text.Trim());
                // 验证发件邮箱地址和密码
                SetAddressForm(this.txtEamilFrom.Text.Trim(), this.txtformPwd.Text.Trim());
                vMailMessage = new MailMessage();
                // 添加收件人邮箱地址
                foreach (DataGridViewRow vRow in grdEmails.Rows)
                {
                    vMailAddressTo = new MailAddress(vRow.Cells[0].Value.ToString().Trim());
                    vMailMessage.To.Add(vMailAddressTo);
                }
                // 发件人邮箱
                vMailMessage.From = vMailAddressFrom;
                // 邮件主题
                vMailMessage.Subject = this.txtEmailtitle.Text.Trim();
                vMailMessage.SubjectEncoding = System.Text.Encoding.UTF8;//字体使用的编码
                // 邮件正文
                vMailMessage.Body = this.txtEmailBody.Text.Trim();
                vMailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                // 清空历史附件,以防附件重复发送
                vMailMessage.Attachments.Clear();
                // 添加附件
                for (int i = 0; i < Files.Count; i++)
                {
                    vMailMessage.Attachments.Add(new Attachment(Files[i].ToString().Trim(), MediaTypeNames.Application.Octet));
                }

                // 注册邮件发送完毕后的处理事件
                vSmtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
                appendLogLn("发送中...");
                // 开始发送邮件
                vSmtpClient.SendAsync(vMailMessage, "000000000");
            }
        }

        // 发送邮件后所处理的函数
        private  void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled)
                {
                    appendLogLn("发送已取消!");
                }
                if (e.Error != null)
                {
                    appendLogLn("邮件发送失败!" + "\n" + "技术信息:\n" + "请验证,发件邮箱和密码是否正确!" );
                }
                else
                {
                    appendLogLn("恭喜邮件成功发出!");
                }
            }
            catch (Exception Ex)
            {
                appendLogLn("邮件发送失败");
            }
        }
        #endregion

        #region 日志操作

        // 清空日志
        private void btnClearLog_Click(object sender, EventArgs e)
        {
            this.txtlog.Clear();
        }

        // 不换行追加
        public void appendLog(string message)
        {
            this.txtlog.AppendText(message);
        }

        // 指定加完空几行
        public void appendLogLastLn(string message, int linenum)
        {
            appendLog(message);
            if (linenum == 0) return;
            for (int i = 0; i < linenum; i++)
            {
                appendLog("\n");
            }
        }

        // 换行追加
        public void appendLogLn(string message)
        {
            appendLogLastLn(message, 1);
        }
        #endregion

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 保存服务器地址
            saveServerCmb();
            // 保存邮箱
            saveGrdEmail();
        }
    }
}

以上就是我实现的邮件发送系统的源码,本次实现未考虑是否会被归于垃圾箱和发送限制,有想法和建议的同学们,欢迎评论。

 

 

结语

  • 受益,掌握了C#邮件发送

 

 

技术分享

本站文章为 宝宝巴士 SD.Team 原创,转载务必在明显处注明:(作者官方网站: 宝宝巴士 

转载自【宝宝巴士SuperDo团队】 原文链接: http://www.cnblogs.com/superdo/p/4719135.html

 

[工具-008] C#邮件发送系统

标签:

原文地址:http://www.cnblogs.com/superdo/p/4719135.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!