邮件发送

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.Mail;

using System.Net.Mime;

using System.IO;

  

namespace SendEmail

{

    public partial class frm_Main : Form

    {

        #region fields

        public bool _user = false;

        public bool _password = false;

        public bool _ReceiveEmail = false;

        #endregion

 

        #region constructor(s)

        public frm_Main()

        {

            InitializeComponent();

            InitEvent();

        }

        #endregion

 

        #region InitEvent

        public void InitEvent()

        {

            this.txtUser.Validating += new CancelEventHandler(txtUser_Validating);       

            this.txtReceiveEmail.Validating += new CancelEventHandler(txtReceiveEmail_Validating);

            this.txtPassword.Validating += new CancelEventHandler(txtPassword_Validating);

        }

        #endregion     

 

        #region methods

        #region SendEmail

        /// <summary>

        /// 进行邮件发送

        /// </summary>

        public void SendEmail(string EmialReceive)

        {

            try

            {

                bool ispass = this.ValidateData();

                if (ispass == false) return;

                //确认smtp服务器地址。实例化一个Smtp客户端

                System.Net.Mail.SmtpClient client = new SmtpClient(this.cobSmtp.Text);

                //生成一个发送地址        

                string strSmtp = this.cobSmtp.Text.Substring(this.cobSmtp.Text.IndexOf('.') + 1);

 

                string strFrom = this.txtUser.Text.Trim() + "@" + strSmtp;

                //构造一个发件人地址对象

                MailAddress from = new MailAddress(strFrom, this.txtSendUser.Text, Encoding.UTF8);

                //构造一个收件人地址对象

                MailAddress to = new MailAddress(EmialReceive, this.txtReceiveUser.Text.Trim(), Encoding.UTF8);

 

                System.Net.Mail.MailMessage message = new MailMessage(from, to);

 

 

                //message添加附件

                foreach (TreeNode tnode in this.trvList.Nodes)

                {

                    //得到文件名

                    string fileName = tnode.Text;

                    //判断文件是否存在

                    if (File.Exists(fileName))

                    {

                        //构造一个附件对象

                        Attachment attach = new Attachment(fileName);

                        //得到文件的信息

                        System.Net.Mime.ContentDisposition disposition = attach.ContentDisposition;

                        disposition.CreationDate = File.GetCreationTime(fileName);

                        disposition.ModificationDate = File.GetLastWriteTime(fileName);

                        disposition.ReadDate = File.GetLastAccessTime(fileName);

                        message.Attachments.Add(attach);

                    }

                    else

                    {

                        MessageBox.Show("文件" + fileName + "未找到!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }

                }

 

                //添加邮件主题和内容

                message.Subject = this.txtTitle.Text.Trim();

                message.SubjectEncoding = Encoding.UTF8;

                message.Body = this.txtContent.Text;

                message.BodyEncoding = Encoding.UTF8;

                message.IsBodyHtml = false;

 

                //设置邮件的信息

                client.DeliveryMethod = SmtpDeliveryMethod.Network;

                //如果服务器支持安全连接,则将安全连接设为true

                //gmail支持,163不支持,如果是gmail则一定要将其设为true

                if (this.cobSmtp.Text == "smtp.163.com")

                    client.EnableSsl = false;

                else

                    client.EnableSsl = true;

                client.UseDefaultCredentials = false;

 

                //设置用户名和密码

                string username = this.txtUser.Text.Trim();

                string password = this.txtPassword.Text.Trim();

                System.Net.NetworkCredential credials = new System.Net.NetworkCredential(username, password);

 

                client.Credentials = credials;

 

                //发送邮件

                client.Send(message);

 

                //MessageBox.Show("发送成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                //写入日志操作,提示哪封邮件已经发送成功

            }

            catch (Exception ex)

            {

                //MessageBox.Show(ex.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                //写入日志操作,提示哪封邮件没有发送成功

            }

        }

        #endregion

 

        #region ValidateData

        /// <summary>

        /// 校验数据是否成功

        /// </summary>

        /// <returns>true则表示数据校验通过,false表示校验不通过</returns>

        public bool ValidateData()

        {

            this.txtUser_Validating(null, null);

            this.txtPassword_Validating(null, null);

            this.txtReceiveEmail_Validating(null, null);

            if (_password == false || _ReceiveEmail == false || _user == false)

                return false;

            else

                return true;

 

        }

        #endregion

        #endregion

 

        #region Event Handlers

        #region Load handler for frm_Main

        private void frm_Main_Load(object sender, EventArgs e)

        {

            //添加两个smtp服务器名称

            this.cobSmtp.Items.Add("smtp.163.com");

            this.cobSmtp.Items.Add("smtp.gmail.com");         

            //设置为下拉列表

            this.cobSmtp.DropDownStyle = ComboBoxStyle.DropDownList;

            //默认选中第一个选项

            this.cobSmtp.SelectedIndex = 0;

            this.txtUser.Text = "用户名";

            this.txtSendUser.Text = "发件人姓名";

            this.txtPassword.Text = "密码";

            this.txtReceiveUser.Text = "收件人姓名";

            this.txtReceiveEmail.Text = "收件人Email";

        }

        #endregion

 

        #region Click handler for btnDel

        private void btnDel_Click(object sender, EventArgs e)

        {

            if (this.trvList.SelectedNode != null)

            {

                TreeNode tempNode = this.trvList.SelectedNode;

                this.trvList.Nodes.Remove(tempNode);

            }

            else

            {

                MessageBox.Show("请选择要删除的附件!","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);

            }

        }

        #endregion

 

        #region Click handler for btnAdd

        private void btnAdd_Click(object sender, EventArgs e)

        {

            OpenFileDialog openfile = new OpenFileDialog();

            openfile.InitialDirectory = Application.StartupPath;

            openfile.FileName = "";

            openfile.RestoreDirectory = true;

            openfile.Multiselect = true;//支持文件多选

            //显示打开文件对话框,并判断是否单击了确定按钮

            if (openfile.ShowDialog() == DialogResult.OK)

            {

                //string fileName = openfile.FileName;

                //this.trvList.Nodes.Add(fileName);

                string[] fileNames = openfile.FileNames;

                foreach (string str in fileNames)

                {

                    this.trvList.Nodes.Add(str);

                }

            }

        }

        #endregion

 

        #region Click handler for btnSend

        private void btnSend_Click(object sender, EventArgs e)

        {

            bool validatePass = this.ValidateData();

            if (validatePass == false) return;

            string[] receives = this.txtReceiveEmail.Text.Trim().Split(new char[] { ';', ',' });

            //支持群发,输入格式为: abc@163.com;def@hotmail.com,ghi@qq.com,如果觉得群发比较慢,可以考虑使用多线程

            foreach (string str in receives)

            {

                this.SendEmail(str.Trim());

            }

            MessageBox.Show("发送完成!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        #endregion

 

        #region Validating handler for txtPassword

        void txtPassword_Validating(object sender, CancelEventArgs e)

        {

            if (this.txtPassword.Text == string.Empty)

            {

                this.errorProvider.SetError(this.txtPassword, "密码不能为空!");

                _password = false;

            }

            else

            {

                this.errorProvider.SetError(this.txtPassword, "");

                _password = true;

            }

        }

        #endregion

 

        #region Validating handler for txtReceiveEmail

        void txtReceiveEmail_Validating(object sender, CancelEventArgs e)

        {

            System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(@"/w+([-+.']/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*");

            if (!rex.IsMatch(this.txtReceiveEmail.Text.Trim()))

            {

                this.errorProvider.SetError(this.txtReceiveEmail, "邮箱地址格式不正确!");

                _ReceiveEmail = false;

            }

            else

            {

                this.errorProvider.SetError(this.txtReceiveEmail, "");

                _ReceiveEmail = true;

            }

        }

        #endregion

 

        #region Validating handler for txtUser

        void txtUser_Validating(object sender, CancelEventArgs e)

        {

            if (this.txtUser.Text == string.Empty)

            {

                this.errorProvider.SetError(this.txtUser, "用户名不能为空!");

                _user = false;

            }

            else

            {

                this.errorProvider.SetError(this.txtUser, "");

                _user = true;

            }

        }

        #endregion

        #endregion

    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值