2014-12-21 12:33:02|?次阅读|上传:wustguangh【已有?条评论】发表评论
下面给出一个综合例子:
protected void Button2_Click(object sender, EventArgs e) { //1.邮件消息 MailMessage objMailMessage = new MailMessage(); //源邮件地址 objMailMessage.From = new MailAddress("******@163.com"); //目的邮件地址,也就是发给我哈 objMailMessage.To.Add("******@163.com"); objMailMessage.Subject = "邮件发送标题:你好";//发送邮件的标题 objMailMessage.Body = "邮件发送标内容:测试一下是否发送成功!";//发送邮件的内容 //2.附件 Attachment objMailAttachment; // 创建一个附件对象 objMailAttachment = new Attachment("d: est.jpg");//发送邮件的附件 objMailMessage.Attachments.Add(objMailAttachment );//将附件附加到邮件消息对象中 //3.使用简单邮件传输协议 (SMTP) 来发送电子邮件 SmtpClient smtp = new SmtpClient(); // 提供身份验证的用户名和密码 // 网易邮件用户可能为:username password // Gmail 用户可能为:username@gmail.com password smtp.Credentials = new NetworkCredential("******", "******"); smtp.Port = 25; // Gmail 使用 465 和 587 端口 smtp.Host = "smtp.163.com"; // 如 smtp.163.com, smtp.gmail.com smtp.EnableSsl = false; // 如果使用GMail,则需要设置为true smtp.SendCompleted += new SendCompletedEventHandler(SendMailCompleted); try { smtp.SendAsync(objMailMessage, objMailMessage); } catch (SmtpException ex) { Console.WriteLine(ex.ToString()); } } /// <summary> /// 邮件发送完成的处理函数 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void SendMailCompleted(object sender, AsyncCompletedEventArgs e) { MailMessage mailMsg = (MailMessage)e.UserState; string subject = mailMsg.Subject; if (e.Cancelled) // 邮件被取消 { Console.WriteLine(subject + " 被取消。"); } if (e.Error != null) { Console.WriteLine("错误:" + e.Error.ToString()); } else { Console.WriteLine("发送完成。"); } }
SendMailCompleted是邮件发送完成之后的回调函数!