C#发送邮件实例

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using AutoTimeSet;
using System.Threading;
using AppConfigHelp;


namespace SendEmail
{
    public partial class SendEmail : Form
    {
        public SendEmail()
        {
            InitializeComponent();
        }

        public Thread thread = null;
        public AutoTimeInfo autoTimeInfo;
        public bool ExitThread=false;
        public struct AutoTimeInfo
        {
            public int Weekend;
            public int Hour;
            public int Minite;

        }
        public void ThreadFunction()
        {
            string compare = "0";
            string tempMode = APPConfigHelper.GetValue("AutoSendMode", "");
            if(tempMode=="0")
            {
                compare = "0";
            }
            else if(tempMode=="1")
            {
                compare = "1";

            }
            int week = 0;        
            int hour = 0;
            int minit = 0;
            ExitThread = false;
            bool enableSend = false;
            bool checkTime=true;
          while(true)
          {

              DateTime dt = DateTime.Now;
                if(compare=="0")
                {
                    week = (int)dt.DayOfWeek;
                }
                else if(compare=="1")
                {
                    week = (int)dt.Day;

                }
            
              hour = dt.Hour;
              minit = dt.Minute;
              if(checkTime)
              {
              if(autoTimeInfo.Weekend==week&&autoTimeInfo.Hour==hour&&autoTimeInfo.Minite==minit)
              {

                  enableSend = true;
                  checkTime = false;

              }
            
              }
              if (autoTimeInfo.Weekend != week || autoTimeInfo.Hour != hour ||autoTimeInfo.Minite != minit)
              {
                  enableSend = false;
                  checkTime = true;
              }

              if(enableSend)
              {
                  this.Invoke(new Action(()=>{
                      Send();
                      enableSend = false;
                  
                  }));
                

              }
              if(ExitThread)
              {
                  return;
              }
              Thread.Sleep(2);
          }

        }

        public void Send()
        {
            EmailInfo emailInfo = new EmailInfo();
            emailInfo.Receive =  APPConfigHelper.GetValue("ReceiveEmail", "");
           emailInfo.Copy= APPConfigHelper.GetValue("CopyEmail", "");
            emailInfo.SendIP = APPConfigHelper.GetValue("SendEmail", "");
           emailInfo.SendPassWord = APPConfigHelper.GetValue("SendEmailPassWord", "");
           emailInfo.SendDisplayName = APPConfigHelper.GetValue("SendDisplayName", "");
            emailInfo.Subject = textBox_Subjectt.Text;
            emailInfo.Body = textBox_Body.Text;
            emailInfo.OtherFilePath = textBox_OtherFilePath.Text;


            //************************************
      System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
      msg.To.Add(emailInfo.Receive);
      msg.CC.Add(emailInfo.Copy);
      msg.From = new MailAddress(emailInfo.SendIP, emailInfo.SendDisplayName, System.Text.Encoding.UTF8);
      msg.Subject = emailInfo.Subject;//邮件标题    
      msg.SubjectEncoding = System.Text.Encoding.UTF8;//邮件标题编码    
      msg.Body = emailInfo.Body;//邮件内容    
      msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码    
      msg.IsBodyHtml = true;//是否是HTML邮件    
      msg.Priority = MailPriority.Normal;//邮件优先级 
      string sfile = emailInfo.OtherFilePath;//添加附件
            if(sfile!="")
            {
                msg.Attachments.Add(new Attachment(sfile));
            }
     
      SmtpClient client = new SmtpClient();
      client.Credentials = new System.Net.NetworkCredential(emailInfo.SendIP, emailInfo.SendPassWord);
      //注册的邮箱和密码    
      client.Host = "smtp.163.com";//根据邮箱类型固定
      object userState = msg;
      try
      {
        //client.SendAsync(msg, userState);
        client.Send(msg);
        MessageBox.Show("发送成功");
      }
      catch (System.Net.Mail.SmtpException ex)
      {
          MessageBox.Show("发送失败" + Environment.NewLine + ex.ToString());
      }
      
    }

        private void button1_Click(object sender, EventArgs e)//设定
        {
            UserSet userSet = new UserSet();
            if (userSet.ShowDialog() == DialogResult.OK)
            {
                userSet.Close();


            }
            else
            {
                userSet.Close();

            }


        }

        private void button_Send_Click(object sender, EventArgs e)
        {
            Send();
        }

        private void button_SelectPath_Click(object sender, EventArgs e)//邮箱设定
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            if(openFileDialog.ShowDialog()==DialogResult.OK)
            {

                textBox_OtherFilePath.Text = openFileDialog.FileName;
                APPConfigHelper.SetValue("FilePath", textBox_OtherFilePath.Text);

            }
            else
            {
                textBox_OtherFilePath.Text = "";


            }
        }

        private void button_AutoSet_Click(object sender, EventArgs e)//自动设定
        {
            checkBox_AutoSend.Checked = false;
          
            AutoSet autoSet = new AutoSet();
            if(autoSet.ShowDialog()==DialogResult.OK)
            {
                string tempStr = "";
                tempStr += autoSet.textBox_WeeKend.Text + "^" + autoSet.textBox_Hour.Text + "^" + autoSet.textBox_Minite.Text;
                if(autoSet.radioButton_WeekSet.Checked)
                {
                    APPConfigHelper.SetValue("AutoTimeSetOfWeekend", tempStr);
                    tempStr = APPConfigHelper.GetValue("AutoTimeSetOfWeekend", "");
                    string[] tempStrs = tempStr.Split('^');
                    autoTimeInfo.Weekend = Convert.ToInt32(tempStrs[0]);
                    autoTimeInfo.Hour = Convert.ToInt32(tempStrs[1]);
                    autoTimeInfo.Minite = Convert.ToInt32(tempStrs[2]);

                }
                else if(autoSet.radioButton_MonthSet.Checked)
                {

                    APPConfigHelper.SetValue("AutoTimeSetOfMonth", tempStr);
                    tempStr = APPConfigHelper.GetValue("AutoTimeSetOfMonth", "");
                    string[] tempStrs = tempStr.Split('^');
                    autoTimeInfo.Weekend = Convert.ToInt32(tempStrs[0]);
                    autoTimeInfo.Hour = Convert.ToInt32(tempStrs[1]);
                    autoTimeInfo.Minite = Convert.ToInt32(tempStrs[2]);
                }
                autoSet.Close();
                radioButton_MonthMode.Checked = false;
                radioButton_WeekMode.Checked = false;


            }
            else
            {
                autoSet.Close();
                radioButton_MonthMode.Checked = false;
                radioButton_WeekMode.Checked = false;
                return;
            }

        }

        private void SendEmail_Load(object sender, EventArgs e)
        {
            try
            {
                string tempStr = APPConfigHelper.GetValue("AutoSendMode", "");
                if(tempStr=="0")
                {
                    radioButton_WeekMode.Checked = true;
                }
                else if(tempStr=="1")
                {
                    radioButton_MonthMode.Checked = true;
                }
               

                textBox_OtherFilePath.Text= APPConfigHelper.GetValue("FilePath", "");

            }
            catch(Exception ee)
            {
                MessageBox.Show(ee.ToString());
            }

        }

        private void checkBox_AutoSend_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox_AutoSend.Checked)
            {
                thread = new Thread(ThreadFunction);
                thread.Start();
            }
            else
            {
                ExitThread = true;
                Thread.Sleep(5);
                if(thread!=null)
                {             
                    thread.Abort();
                  
                }

            }
            
        }

        private void radioButton_WeekMode_CheckedChanged(object sender, EventArgs e)
        {
            string tempStr = "";
            if(radioButton_WeekMode.Checked)
            {
                APPConfigHelper.SetValue("AutoSendMode", "0");
                tempStr = APPConfigHelper.GetValue("AutoTimeSetOfWeekend", "");
                string[] tempStrs = tempStr.Split('^');
                autoTimeInfo.Weekend = Convert.ToInt32(tempStrs[0]);
                autoTimeInfo.Hour = Convert.ToInt32(tempStrs[1]);
                autoTimeInfo.Minite = Convert.ToInt32(tempStrs[2]);
            }
            else if(radioButton_MonthMode.Checked)
            {

                APPConfigHelper.SetValue("AutoSendMode", "1");
                tempStr = APPConfigHelper.GetValue("AutoTimeSetOfMonth", "");
                string[] tempStrs = tempStr.Split('^');
                autoTimeInfo.Weekend = Convert.ToInt32(tempStrs[0]);
                autoTimeInfo.Hour = Convert.ToInt32(tempStrs[1]);
                autoTimeInfo.Minite = Convert.ToInt32(tempStrs[2]);
            }

        }
    }
    public class EmailInfo
    {
        public string Receive { get; set; }//接收者
        public string Copy { get; set; }//抄送者
        public string SendIP { get; set; }//发送方
        public string SendPassWord { get; set; }//密码
        public string SendDisplayName { get; set; }//发送者显示

        public string Subject { get; set; }//邮件主题
        public string Body { get; set; }//邮件内容

        public string OtherFilePath { get; set; }//附件

     //调用
/*
    Email email = new Email();
    email.mailFrom = "";//发送人的邮箱地址
    email.mailPwd = "";//发送人邮箱的密码
    email.mailSubject = "";//邮件主题
    email.mailBody = "";//邮件内容
    email.isbodyHtml = true;    //是否是HTML
    email.host = "smtp.163.com";//如果是QQ邮箱则:smtp:qq.com,依次类推
    email.mailToArray = new string[] { "3***[email protected]" };//接收者邮件集合
    //email.mailCcArray = new string[] { "******@qq.com" };//抄送者邮件集合
    email.Send().ToString();
 * */

    }
}
 

猜你喜欢

转载自blog.csdn.net/u011555996/article/details/86483833