NET实现发送邮件
1.以QQ邮箱为例,首先打开QQ邮箱设置的账户,将对应的服务启动。

2.前台如下:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Start.aspx.cs" Inherits="Tset.Start" %> 2 3 <!DOCTYPE html> 4 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 8 <title></title> 9 </head> 10 <body> 11 <form id="form1" runat="server"> 12 <div> 13 <asp:Button ID="btnStart" runat="server" Text="发送" OnClick="btnStart_Click" /> 14 <asp:Label ID="labInfo" runat="server" Visible="False" ForeColor="#FF0066"></asp:Label> 15 </div> 16 </form> 17 </body> 18 </html>
3.后台代码如下:
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.Text; 10 using System.Net.Mime; 11 12 namespace Tset 13 { 14 public partial class Start : System.Web.UI.Page 15 { 16 protected void Page_Load(object sender, EventArgs e) 17 { 18 19 } 20 21 protected void btnStart_Click(object sender, EventArgs e) 22 { 23 MailMessage msg = new MailMessage(); 24 msg.To.Add("XXX@qq.com");//收件人邮箱 25 msg.CC.Add("XXX@163.com");//抄送人邮箱 26 msg.From = new MailAddress("XXX@qq.com", "嘿嘿");//发件人的邮箱,发件人的名称 27 28 msg.Subject = "XXXX";//邮件主题 29 msg.SubjectEncoding = Encoding.UTF8;//邮件主题格式为UTF8 30 msg.IsBodyHtml = true;//邮件正文为HTML格式 31 msg.Body = "<a href='http://www.baidu.com' style='color:red'>www.baidu.com</a>";//邮件正文 32 msg.BodyEncoding = Encoding.UTF8;//邮件正文格式为UTF8 33 34 msg.Attachments.Add(new Attachment(@"D:\a.jpg", MediaTypeNames.Image.Jpeg));//图像附件 35 msg.Attachments.Add(new Attachment(@"D:\b.zip", "application/x-zip-compressed"));//ZIP附件 36 37 SmtpClient client = new SmtpClient(); 38 client.Host = "smtp.qq.com";//SMTP服务器地址 39 client.Port = 25;//SMTP端口 40 client.EnableSsl = true;//启用SSL加密 41 client.UseDefaultCredentials = true; 42 client.Credentials = new NetworkCredential("XXXX@qq.com", "XXXXX");//发件人邮箱,授权码 43 try 44 { 45 client.Send(msg); //发送邮件 46 labInfo.Visible = true; 47 labInfo.Text = "发送成功!"; 48 } 49 catch (Exception ex) 50 { 51 labInfo.Visible = true; 52 labInfo.Text = "发送失败!失败原因:" + ex.Message.ToString(); 53 } 54 } 55 } 56 }

浙公网安备 33010602011771号