首页 > 代码库 > .Net实现简单的邮件发送
.Net实现简单的邮件发送
使用winform写了一个小程序,实现简单的邮件发送功能,部分代码如下:
//异步发送邮件:
1 //发送按钮 2 private void btn_Send_Click(object sender, EventArgs e) 3 { 4 //创建MailMessage对象 5 MailAddress from = new MailAddress("ntsmtp@163.com"); 6 MailAddress to = new MailAddress("miaosha5s@sohu.com"); 7 MailMessage mailMessage = new MailMessage(from, to) ; 8 mailMessage.Subject="主题"; 9 mailMessage.Body="这是一封来自远方的邮件."; 10 11 Attachment attachment01 = new Attachment("E:\\01.jpg"); //附件12 Attachment attachment02 = new Attachment("E:\\02.mp3");13 mailMessage.Attachments.Add(attachment01);14 mailMessage.Attachments.Add(attachment02);15 16 //创建SmtpClient对象 邮箱服务器smtp.163.com17 SmtpClient smtpClient = new SmtpClient("smtp.163.com"); 18 smtpClient.UseDefaultCredentials = true;19 smtpClient.Credentials =20 new NetworkCredential("邮箱账号", "登录密码"); //邮箱认证登录21 //smtpClient.Timeout = 5000;22 try23 {24 //使用异步发送,不会阻塞该线程25 smtpClient.SendCompleted += new //完成发送调用回调函数26 SendCompletedEventHandler(SendCompletedCallback); 27 smtpClient.SendAsync(mailMessage, mailMessage); 28 }29 catch(Exception ex)30 {31 mailMessage.Dispose(); //主动释放资源32 smtpClient.Dispose();33 MessageBox.Show("发送失败! "+System.Environment.NewLine+34 "错误信息:"+ ex.Message);35 }36 return;37 }
//异步发送完成的回调函数:
1 //异步发送邮件完成的回调函数 2 public static void SendCompletedCallback(object sender, 3 AsyncCompletedEventArgs e) 4 { 5 SmtpClient smtpClient = (SmtpClient)sender; 6 //MailMessage mailMessage = (MailMessage)e.UserState; 7 if (e.Cancelled) 8 { 9 MessageBox.Show("Send canceled.");10 }11 if (e.Error != null) 12 {13 MessageBox.Show("错误信息: "+e.Error.ToString() );14 }15 else16 {17 MessageBox.Show("Message Sent.");18 smtpClient.Dispose();19 //mailMessage.Dispose();20 }21 }
.Net实现简单的邮件发送
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。