zoukankan      html  css  js  c++  java
  • 使用C# 发送Email 邮件方法

    废话少说,直接贴代码。
     
    1:  usingSystem;
       2:  usingSystem.Collections.Generic;
       3:  usingSystem.ComponentModel;
       4:  usingSystem.Data;
       5:  usingSystem.Drawing;
       6:  usingSystem.Text;
       7:  usingSystem.Windows.Forms;
       8:  usingSystem.Net.Mail;
       9:  usingSystem.Net.Mime;
      10:  usingSystem.IO;
      11:    
      12:  namespaceSendEmail
      13:  {
      14:     publicpartialclassfrm_Main:Form
      15:     {
      16:         #regionfields
      17:         publicbool_user =false;
      18:         publicbool_password =false;
      19:         publicbool_ReceiveEmail =false;
      20:         #endregion
      21:   
      22:         #regionconstructor(s)
      23:         publicfrm_Main()
      24:         {
      25:             InitializeComponent();
      26:             InitEvent();
      27:         }
      28:         #endregion
      29:   
      30:         #regionInitEvent
      31:         publicvoidInitEvent()
      32:         {
      33:             this.txtUser.Validating +=newCancelEventHandler(txtUser_Validating);       
      34:             this.txtReceiveEmail.Validating +=newCancelEventHandler(txtReceiveEmail_Validating);
      35:             this.txtPassword.Validating +=newCancelEventHandler(txtPassword_Validating);
      36:         }
      37:         #endregion     
      38:   
      39:         #regionmethods
      40:         #regionSendEmail
      41:         ///<summary>
      42:         ///进行邮件发送
      43:         ///</summary>
      44:         publicvoidSendEmail(stringEmialReceive)
      45:         {
      46:             try
      47:             {
      48:                 boolispass =this.ValidateData();
      49:                 if(ispass ==false)return;
      50:                 //确认smtp服务器地址。实例化一个Smtp客户端
      51:                 System.Net.Mail.SmtpClientclient =newSmtpClient(this.cobSmtp.Text);
      52:                 //生成一个发送地址        
      53:                 stringstrSmtp =this.cobSmtp.Text.Substring(this.cobSmtp.Text.IndexOf('.') + 1);
      54:   
      55:                 stringstrFrom =this.txtUser.Text.Trim() +"@"+ strSmtp;
      56:                 //构造一个发件人地址对象
      57:                 MailAddressfrom =newMailAddress(strFrom,this.txtSendUser.Text,Encoding.UTF8);
      58:                 //构造一个收件人地址对象
      59:                 MailAddressto =newMailAddress(EmialReceive,this.txtReceiveUser.Text.Trim(),Encoding.UTF8);
      60:   
      61:                 System.Net.Mail.MailMessagemessage =newMailMessage(from, to);
      62:   
      63:   
      64:                 //为message添加附件
      65:                 foreach(TreeNodetnodeinthis.trvList.Nodes)
      66:                 {
      67:                     //得到文件名
      68:                     stringfileName = tnode.Text;
      69:                     //判断文件是否存在
      70:                     if(File.Exists(fileName))
      71:                     {
      72:                         //构造一个附件对象
      73:                         Attachmentattach =newAttachment(fileName);
      74:                         //得到文件的信息
      75:                         System.Net.Mime.ContentDispositiondisposition = attach.ContentDisposition;
      76:                         disposition.CreationDate =File.GetCreationTime(fileName);
      77:                         disposition.ModificationDate =File.GetLastWriteTime(fileName);
      78:                         disposition.ReadDate =File.GetLastAccessTime(fileName);
      79:                         message.Attachments.Add(attach);
      80:                     }
      81:                     else
      82:                     {
      83:                         MessageBox.Show("文件"+ fileName +"未找到!","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
      84:                     }
      85:                 }
      86:   
      87:                 //添加邮件主题和内容
      88:                 message.Subject =this.txtTitle.Text.Trim();
      89:                 message.SubjectEncoding =Encoding.UTF8;
      90:                 message.Body =this.txtContent.Text;
      91:                 message.BodyEncoding =Encoding.UTF8;
      92:                 message.IsBodyHtml =false;
      93:   
      94:                 //设置邮件的信息
      95:                 client.DeliveryMethod =SmtpDeliveryMethod.Network;
      96:                 //如果服务器支持安全连接,则将安全连接设为true。
      97:                 //gmail支持,163不支持,如果是gmail则一定要将其设为true
      98:                 if(this.cobSmtp.Text =="smtp.163.com")
      99:                     client.EnableSsl =false;
     100:                 else
     101:                     client.EnableSsl =true;
     102:                 client.UseDefaultCredentials =false;
     103:   
     104:                 //设置用户名和密码
     105:                 stringusername =this.txtUser.Text.Trim();
     106:                 stringpassword =this.txtPassword.Text.Trim();
     107:                 System.Net.NetworkCredentialcredials =newSystem.Net.NetworkCredential(username, password);
     108:   
     109:                 client.Credentials = credials;
     110:   
     111:                 //发送邮件
     112:                 client.Send(message);
     113:   
     114:                 //MessageBox.Show("发送成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
     115:                 //写入日志操作,提示哪封邮件已经发送成功
     116:             }
     117:             catch(Exceptionex)
     118:             {
     119:                 //MessageBox.Show(ex.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
     120:                 //写入日志操作,提示哪封邮件没有发送成功
     121:             }
     122:         }
     123:         #endregion
     124:   
     125:         #regionValidateData
     126:         ///<summary>
     127:         ///校验数据是否成功
     128:         ///</summary>
     129:         ///<returns>true则表示数据校验通过,false表示校验不通过</returns>
     130:         publicboolValidateData()
     131:         {
     132:             this.txtUser_Validating(null,null);
     133:             this.txtPassword_Validating(null,null);
     134:             this.txtReceiveEmail_Validating(null,null);
     135:             if(_password ==false|| _ReceiveEmail ==false|| _user ==false)
     136:                 returnfalse;
     137:             else
     138:                 returntrue;
     139:   
     140:         }
     141:         #endregion
     142:         #endregion
     143:   
     144:         #regionEvent Handlers
     145:         #regionLoad handler for frm_Main
     146:         privatevoidfrm_Main_Load(objectsender,EventArgse)
     147:         {
     148:             //添加两个smtp服务器名称
     149:             this.cobSmtp.Items.Add("smtp.163.com");
     150:             this.cobSmtp.Items.Add("smtp.gmail.com");         
     151:             //设置为下拉列表
     152:             this.cobSmtp.DropDownStyle =ComboBoxStyle.DropDownList;
     153:             //默认选中第一个选项
     154:             this.cobSmtp.SelectedIndex = 0;
     155:             this.txtUser.Text ="用户名";
     156:             this.txtSendUser.Text ="发件人姓名";
     157:             this.txtPassword.Text ="密码";
     158:             this.txtReceiveUser.Text ="收件人姓名";
     159:             this.txtReceiveEmail.Text ="收件人Email";
     160:         }
     161:         #endregion
     162:   
     163:         #regionClick handler for btnDel
     164:         privatevoidbtnDel_Click(objectsender,EventArgse)
     165:         {
     166:             if(this.trvList.SelectedNode !=null)
     167:             {
     168:                 TreeNodetempNode =this.trvList.SelectedNode;
     169:                 this.trvList.Nodes.Remove(tempNode);
     170:             }
     171:             else
     172:             {
     173:                 MessageBox.Show("请选择要删除的附件!","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
     174:             }
     175:         }
     176:         #endregion
     177:   
     178:         #regionClick handler for btnAdd
     179:         privatevoidbtnAdd_Click(objectsender,EventArgse)
     180:         {
     181:             OpenFileDialogopenfile =newOpenFileDialog();
     182:             openfile.InitialDirectory =Application.StartupPath;
     183:             openfile.FileName ="";
     184:             openfile.RestoreDirectory =true;
     185:             openfile.Multiselect =true;//支持文件多选
     186:             //显示打开文件对话框,并判断是否单击了确定按钮
     187:             if(openfile.ShowDialog() ==DialogResult.OK)
     188:             {
     189:                 //string fileName = openfile.FileName;
     190:                 //this.trvList.Nodes.Add(fileName);
     191:                 string[] fileNames = openfile.FileNames;
     192:                 foreach(stringstrinfileNames)
     193:                 {
     194:                     this.trvList.Nodes.Add(str);
     195:                 }
     196:             }
     197:         }
     198:         #endregion
     199:   
     200:         #regionClick handler for btnSend
     201:         privatevoidbtnSend_Click(objectsender,EventArgse)
     202:         {
     203:             boolvalidatePass =this.ValidateData();
     204:             if(validatePass ==false)return;
     205:             string[] receives =this.txtReceiveEmail.Text.Trim().Split(newchar[] {';',','});
     206:              //支持群发,输入格式为:abc@163.com;def@hotmail.com,ghi@qq.com,如果觉得群发比较慢,可以考虑使用多线程
     207:             foreach(stringstrinreceives)
     208:             {
     209:                 this.SendEmail(str.Trim());
     210:             }
     211:             MessageBox.Show("发送完成!","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
     212:         }
     213:         #endregion
     214:   
     215:         #regionValidating handler for txtPassword
     216:         voidtxtPassword_Validating(objectsender,CancelEventArgse)
     217:         {
     218:             if(this.txtPassword.Text ==string.Empty)
     219:             {
     220:                 this.errorProvider.SetError(this.txtPassword,"密码不能为空!");
     221:                 _password =false;
     222:             }
     223:             else
     224:             {
     225:                 this.errorProvider.SetError(this.txtPassword,"");
     226:                 _password =true;
     227:             }
     228:         }
     229:         #endregion
     230:   
     231:         #regionValidating handler for txtReceiveEmail
     232:         voidtxtReceiveEmail_Validating(objectsender,CancelEventArgse)
     233:         {
     234:             System.Text.RegularExpressions.Regexrex =newSystem.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
     235:             if(!rex.IsMatch(this.txtReceiveEmail.Text.Trim()))
     236:             {
     237:                 this.errorProvider.SetError(this.txtReceiveEmail,"邮箱地址格式不正确!");
     238:                 _ReceiveEmail =false;
     239:             }
     240:             else
     241:             {
     242:                 this.errorProvider.SetError(this.txtReceiveEmail,"");
     243:                 _ReceiveEmail =true;
     244:             }
     245:         }
     246:         #endregion
     247:   
     248:         #regionValidating handler for txtUser
     249:         voidtxtUser_Validating(objectsender,CancelEventArgse)
     250:         {
     251:             if(this.txtUser.Text ==string.Empty)
     252:             {
     253:                 this.errorProvider.SetError(this.txtUser,"用户名不能为空!");
     254:                 _user =false;
     255:             }
     256:             else
     257:             {
     258:                 this.errorProvider.SetError(this.txtUser,"");
     259:                 _user =true;
     260:             }
     261:         }
     262:     
    264: } 265: }

      

  • 相关阅读:
    自定义Response
    并发编程之进程
    并发编程知识储备
    正则表达式和re模块
    Scrapy框架
    http协议和Chrome抓包工具
    requests库
    Beautifulsoup
    xpath
    Mysql一些操作
  • 原文地址:https://www.cnblogs.com/360aq/p/2511108.html
Copyright © 2011-2022 走看看