前言
很多时候,我们是需要发送邮件的功能的。以下是我的一个测试例子,用的是QQ的服务器(smtp.qq.com)
第一步,新建一个操作邮件的类,代码如下:
class="code_img_closed" src="/Upload/Images/2013121818/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('0f909643-9f49-4a88-8828-a2e872e6e14b',event)" src="/Upload/Images/2013121818/2B1B950FA3DF188F.gif" alt="" />1 using System; 2 using System.Collections; 3 using System.Net.Mail; 4 namespace Ajax 5 { 6 public class MailUnit 7 { 8 private string smtp; 9 private string from; 10 private string pwd; 11 private string to; 12 private string title; 13 private string body; 14 private ArrayList paths; 15 /// <summary> 16 /// 发送邮件单元类 17 /// </summary> 18 /// <param name="Psmtp">SMTP服务器地址(smtp.qq.com)</param> 19 /// <param name="Pfrom">发件人地址</param> 20 /// <param name="Ppwd">发件人密码</param> 21 /// <param name="Pto">收件人地址</param> 22 /// <param name="Ptitle">主题</param> 23 /// <param name="Pbody">正文</param> 24 /// <param name="Ppaths">附件</param> 25 public MailUnit(string Psmtp, string Pfrom, string Ppwd, string Pto, string Ptitle, string Pbody, ArrayList Ppaths) 26 { 27 smtp = Psmtp; from = Pfrom; pwd = Ppwd; to = Pto; title = Ptitle; body = Pbody; paths = Ppaths; 28 } 29 /*发邮件*/ 30 public bool SendMail() 31 { 32 //创建smtpclient对象 33 SmtpClient client = new SmtpClient(); //微软已经提供了发送邮件的基础类库,调用就可以了。 34 client.Host = smtp; 35 client.UseDefaultCredentials = false; 36 client.Credentials = new System.Net.NetworkCredential(from, pwd); 37 client.DeliveryMethod = SmtpDeliveryMethod.Network; 38 //创建mailMessage对象 39 System.Net.Mail.MailMessage message = new MailMessage(from, to); 40 message.Subject = title; 41 //正文默认格式为html 42 message.Body = body; 43 message.IsBodyHtml = true; 44 message.BodyEncoding = System.Text.Encoding.UTF8; 45 //添加附件 46 if (paths!=null && paths.Count != 0) 47 { 48 foreach (string path in paths) 49 { 50 Attachment data = new Attachment(path, System.Net.Mime.MediaTypeNames.Application.Octet); 51 message.Attachments.Add(data); 52 } 53 } 54 try { client.Send(message); return true; }//MessageBox.Show("邮件发送成功."); 55 catch (Exception ex) { return false; }//MessageBox.Show("邮件发送失败." + ex.ToString()); 56 } 57 } 58 }View Code
第二步,调用操作类,代码如下:
1 MailUnit mail = new MailUnit("SMTP服务器地址", "发件人地址", "发件人密码", "收件人地址", "我的第一封邮件", "希望邮件发送成功", null);//因为是测试,发件人地址用的是自己的QQ号。 2 if (mail.SendMail()) 3 { 4 Response.Write("<script>alert('发送成功');</script>"); 5 } 6 else 7 { 8 Response.Write("<script>alert('发送失败');</script>"); 9 }View Code
第三步,设置(用自己的QQ号作为发送人,所以要设置一下QQ账号):
QQ邮箱->设置->账号->设置成下图:
Tencent/Users/879211310/QQ/WinTemp/RichOle/O2V3RJWXLZZX`}[B@%$1R_N.jpg" alt="" /> 到此,就可以实现发邮件的功能。 注意:QQ服务器只是可以用来测试,用的过多,可能你的QQ会被封号。如果滥用,造成的后果与本人无关