最近在做一个发送邮件的功能,在网上找了半天,找到两个简单的发送方法,一个System.web.mail的发送方法,具体有什么区别我也没弄清楚,还要做把发送的邮件备份到已发送中去,也没搞定
/// <summary> /// System.web.Mail的邮件发送方法 /// </summary> /// <param name='clientHost'>邮件服务器地址</param> /// <param name='emailAddress'>发件人邮箱地址</param> /// <param name='receiveAddress'>收件人邮箱地址</param> /// <param name='userName'>发件人邮箱用户名</param> /// <param name='password'>发件人邮箱密码</param> /// <param name="subject">邮件主题</param> /// <param name="body">邮件正文</param> public string andEmail(string clientHost, string emailAddress, string receiveAddress,string userName, string password, string subject, string body) { System.Web.Mail.MailMessage objMailMessage; // MailAttachment objMailAttachment; // 创建一个附件对象 // objMailAttachment = new MailAttachment( "d://test.txt" );//发送邮件的附件 // 创建邮件消息 objMailMessage = new System.Web.Mail.MailMessage(); objMailMessage.From = emailAddress;//源邮件地址 objMailMessage.To = receiveAddress;//目的邮件地址 objMailMessage.Subject = subject;//发送邮件的标题 objMailMessage.BodyFormat = MailFormat.Html; objMailMessage.Body = body;//发送邮件的内容 // objMailMessage.Attachments.Add( objMailAttachment );//将附件附加到邮件消息对象中 //接着利用sina的SMTP来发送邮件,需要使用Microsoft .NET Framework SDK v1.1和它以上的版本 //基本权限 objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //用户名 objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", userName); //密码 objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", password); //如果没有上述三行代码,则出现如下错误提示:服务器拒绝了一个或多个收件人地址。服务器响应为: 554 : Client host rejected: Access denied //SMTP地址 SmtpMail.SmtpServer = clientHost; try { //开始发送邮件 SmtpMail.Send(objMailMessage); } catch (Exception ex) { return ex.ToString(); } return "成功"; }
system.NEt 。mail的方法
/// <summary> /// System.NET.Mail的邮件发送方法 /// </summary> /// <param name='clientHost'>邮件服务器地址</param> /// <param name='emailAddress'>发件人邮箱地址</param> /// <param name='receiveAddress'>收件人邮箱地址</param> /// <param name='userName'>发件人邮箱用户名</param> /// <param name='password'>发件人邮箱密码</param> /// <param name="subject">邮件主题</param> /// <param name="body">邮件正文</param> public void SendEmail(string clientHost, string emailAddress, string receiveAddress, string userName, string password, string subject, string body) { System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage(); mail.From = new MailAddress(emailAddress); mail.To.Add(new MailAddress(receiveAddress)); mail.Subject = subject; mail.Body = body; mail.IsBodyHtml = true; mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess; SmtpClient client = new SmtpClient(); client.Host = clientHost; client.Credentials = new NetworkCredential(userName, password); client.DeliveryMethod = SmtpDeliveryMethod.Network; //client.UseDefaultCredentials = true; try { client.Send(mail); } catch (Exception ex) { Response.Write(ex); // Get ex.Message and do something } }