asp.net 带附件发送邮件

来源:互联网 发布:成都行知小学对口中学 编辑:程序博客网 时间:2024/05/17 09:37

在51aspx.com下了个发邮件的,不过不怎么好用,也没有详细的说明,也没有发送成功,

 

在网上找了一个类说明,结合了一下,重新写了,只要再改动一下,就很实用了。

 

引用三个类:

  1. using System.Net.Mail;
  2. using System.Net;
  3. using System.Net.Mime;
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.Net.Mail;
  8. using System.Net;
  9. using System.Net.Mime;
  10. public partial class test_sendMail : System.Web.UI.Page
  11. {
  12.     protected void Page_Load(object sender, EventArgs e)
  13.     {
  14.     }
  15.     protected void Button1_Click(object sender, EventArgs e)
  16.     {
  17.         MailMessage mailMsg = new MailMessage();
  18.         mailMsg.From = new MailAddress("*****@163.com");//发送邮件用户名
  19.         mailMsg.To.Add("*******@163.com");//接收邮件用户
  20.         mailMsg.Subject = "邮件主题";
  21.         mailMsg.Body = "邮件主体内容ffffffffffffffffffff";
  22.         mailMsg.BodyEncoding = System.Text.Encoding.UTF8;
  23.         mailMsg.IsBodyHtml = false;
  24.         mailMsg.Priority = MailPriority.High;
  25.         string file = Request.PhysicalApplicationPath + "test//data.xls";  //附件的地址
  26.         // Create  the file attachment for this e-mail message.
  27.         Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
  28.         // Add time stamp information for the file.
  29.         ContentDisposition disposition = data.ContentDisposition;
  30.         disposition.CreationDate = System.IO.File.GetCreationTime(file);
  31.         disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
  32.         disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
  33.         mailMsg.Attachments.Add(data);
  34.         SmtpClient smtp = new SmtpClient();
  35.         // 提供身份验证的用户名和密码 
  36.         // 网易邮件用户可能为:username password 
  37.         // Gmail 用户可能为:username@gmail.com password 
  38.         smtp.Credentials = new NetworkCredential("userName""userpwd");
  39.         smtp.Port = 25; // Gmail 使用 465 和 587 端口 
  40.         smtp.Host = "smtp.163.com"// 如 smtp.163.com, smtp.gmail.com 
  41.         smtp.EnableSsl = false// 如果使用GMail,则需要设置为true 
  42.         //smtp.SendCompleted += new SendCompletedEventHandler(SendMailCompleted);
  43.         smtp.SendAsync(mailMsg, mailMsg);
  44.     }
  45. }

 

163测试成功,Gmail未测试。。。。

原创粉丝点击