MailMessage、Smtp发送邮件

保证SMTP服务的正确安装以及配置,还要适当的设置中继限制

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.Web;
using System.Xml;
using System.ServiceProcess;
using System.Collections;
namespace mail
{
    public partial class SendMailFrm : Form
    {
        private ArrayList  Attacments;
        private SmtpClient MySmtpClient;
        private MailAddress from;
        private MailAddress to;
        private MailMessage msg;
        private string SysParXmlPath;
        private XmlDocument SysParXml;
        private XmlElement MailFrom;
        private XmlElement MailFromName;
        private XmlElement MailTo;
        private XmlElement MailToName;
        public SendMailFrm()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            InitSmptServer();
            InitComBoxPriority();
            SysParXmlPath =@"../../Data/SysPar.xml";
            LoadLastMail();
        }
        private void LoadLastMail()
        {
            if (SysParXml ==null )
                SysParXml = new XmlDocument();
            SysParXml.Load(SysParXmlPath);
            MailFrom = (XmlElement)SysParXml.SelectSingleNode("/SysParameter/LastMailMessage/MailFrom");
            MailFromName = (XmlElement)SysParXml.SelectSingleNode("/SysParameter/LastMailMessage/MailFromName");
            MailTo = (XmlElement)SysParXml.SelectSingleNode("/SysParameter/LastMailMessage/MailTo");
            MailToName = (XmlElement)SysParXml.SelectSingleNode("/SysParameter/LastMailMessage/MailToName");
            txtMailFrom.Text = MailFrom.InnerText;
            txtMailFromName.Text = MailFromName.InnerText;
            txtMailTo.Text = MailTo.InnerText;
            txtMailToName.Text = MailToName.InnerText;
        }
        private void SaveToLastMail()
        {
             MailFrom.InnerText= txtMailFrom.Text.Trim();
             MailFromName.InnerText=txtMailFromName.Text.Trim() ;
             MailTo.InnerText=txtMailTo.Text.Trim();
             MailToName.InnerText=txtMailToName.Text.Trim();
             SysParXml.Save(SysParXmlPath);
             SysParXml = null;
        }
        private void InitComBoxPriority()
        {
             string[] priority ={ "重要", "普通", "低" };
            comBoxPriority.Items.AddRange(priority);
            comBoxPriority.Text = priority[1];
        }
        private void InitSmptServer()
        {
             ServiceController[] services = ServiceController.GetServices();
            ServiceController service = null;
            bool blnHasSmtpService = false;
            foreach (ServiceController aservice in services)
            {
                if (aservice.ServiceName.ToLower() == "smtpsvc")
                {
                    blnHasSmtpService = true;
                    service = aservice; break;
                }
            }
            if (!blnHasSmtpService)
            {
                MessageBox.Show(this ,"没有安装Smtp服务",this .Text ,MessageBoxButtons .OK ,MessageBoxIcon .Information);
            }
            if (service.Status != ServiceControllerStatus.Running)
            {
                try
                {
                    service.Start();
                }
                catch(Exception ex)
                {
                    MessageBox.Show(this,ex.Message,this .Text ,MessageBoxButtons .OK ,MessageBoxIcon .Information);
                }
            }
        }
        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                btnSend.Enabled = false;
                if (txtMailFromName.TextLength == 0)
                    txtMailFromName.Text = txtMailFrom.Text;
                if (txtMailToName.TextLength == 0)
                    txtMailToName.Text = txtMailTo.Text;
                if (txtSubject.TextLength == 0)
                    txtSubject.Text = "默认主题";
                SendMailMessage();
                lstBoxAttach .Items .Clear ();
                if (Attacments !=null)
                 Attacments .Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
           
        }
        private void SendMailMessage()
        {
                from = null; to = null;
                if (msg != null)
                { msg.Dispose(); msg = null;}
               from = new MailAddress(txtMailFrom.Text.Trim (),txtMailFromName .Text .Trim ());
               to = new MailAddress(txtMailTo.Text .Trim(),txtMailToName .Text .Trim ());
               msg = new MailMessage(from, to);
                    msg.Subject = txtSubject.Text .Trim ();
                    msg.Body = rtbBody.Text;
                    msg.Priority = (MailPriority)comBoxPriority .SelectedIndex;
                    if (Attacments != null)
                    {
                        foreach (Attachment mailAttach in Attacments)
                            msg.Attachments.Add(mailAttach);
                    }
                    if (MySmtpClient ==null)
                    MySmtpClient = new SmtpClient("localhost");
                    MySmtpClient.UseDefaultCredentials = false;
               // MySmtpClient.Send(msg);//同步发送
                    MySmtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
                    MySmtpClient.SendAsync(msg,"邮件发送成功!");//异步发送成功
                    //MessageBox.Show(this ,"邮件发送成功",this.Text,MessageBoxButtons .OK ,MessageBoxIcon .Information );
        }
        private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                MessageBox.Show(this, "邮件发送成功", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show(this, e.Error .Message+"/r/n"+e .Error .InnerException .Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            btnSend.Enabled = true;
        }
        private void btnEsc_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAddAttach_Click(object sender, EventArgs e)
        {
            odlgAttachment.InitialDirectory = @"c:/";
            odlgAttachment.Filter = "所有文件(*.*)|*.*|HTML文件(*.htm;*html)|*.htm|Office文件(*.docx,*.xls,*.pptx)|*.docx;*.xls;*.pptx;|文本文件(*.txt)|*.txt";
            odlgAttachment.FilterIndex = 1;
            odlgAttachment.Multiselect = true;
            if (odlgAttachment.ShowDialog() == DialogResult.OK)
            {
                if (Attacments == null)
                {
                    Attacments = new ArrayList();
                    lstBoxAttach.Items.Clear();
                }
                string[] AttachFiles = odlgAttachment.FileNames;
                foreach (string FileName in AttachFiles)
                {
                    Attacments.Add(new Attachment(FileName));
                    lstBoxAttach.Items.Add(FileName);
                }

            }
        }

        private void SendMailFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            SaveToLastMail();
            if (Attacments!=null)
                Attacments.Clear();
                Attacments = null;
                MySmtpClient = null;
        }

        private void btnRemoveAttach_Click(object sender, EventArgs e)
        {
            int index = lstBoxAttach.SelectedIndex;
            if (index >= 0)
            {
                Attacments.RemoveAt(index);
                lstBoxAttach.Items.RemoveAt(index);
                from =null ; to = null; msg.Dispose();
            }
        }

        private void txtMailFrom_Validating(object sender, CancelEventArgs e)
        {
            TextBox txtbox = sender as TextBox;
            if (txtbox !=null )
                try
                {
                    ValidateEmailAddress(txtbox);
                }
                catch (Exception ex)
                {
                    e.Cancel = true;
                    txtbox.Select(0, txtbox.Text.Length);
                    errorProvider.SetError(txtbox, ex.Message);
                }
        }
        private void ValidateEmailAddress(TextBox txtbox)
        {
            if (txtbox.Text.Trim().Length == 0)
                throw new Exception("请您务必输入邮件!");
            else
            {
                if (txtbox.Text.IndexOf(".") == -1 || txtbox.Text.IndexOf("@") == -1)
                    throw new Exception("请输入合法邮箱格式");
            }
        }

        private void txtMailFrom_VisibleChanged(object sender, EventArgs e)
        {
            errorProvider.SetError((TextBox)sender, "");
        }

        private void rtbBody_Click(object sender, EventArgs e)
        {
            if (rtbBody .Text=="请输入正文......")
                rtbBody.Clear();
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值