使用winform写了一个小程序,实现简单的邮件发送功能,部分代码如下:
//异步发送邮件:
1 //发送按钮 2 private void btn_Send_Click(object sender, EventArgs e) 3 { 4 //创建MailMessage对象 5 MailAddress from = new MailAddress("[email protected]"); 6 MailAddress to = new MailAddress("[email protected]"); 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.com 17 SmtpClient smtpClient = new SmtpClient("smtp.163.com"); 18 smtpClient.UseDefaultCredentials = true; 19 smtpClient.Credentials = 20 new NetworkCredential("邮箱账号", "登录密码"); //邮箱认证登录 21 //smtpClient.Timeout = 5000; 22 try 23 { 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 else 16 { 17 MessageBox.Show("Message Sent."); 18 smtpClient.Dispose(); 19 //mailMessage.Dispose(); 20 } 21 }
时间: 2024-10-31 13:55:04