首页 > 技术文章 > ASP.NET发送邮件

bsyblog 2014-12-24 17:50 原文

 

在ASP.NET中实现发送邮件的功能,包括发送附近、HTML页面、图片,并且可以有多个发送对象。

在实际使用中用到队列、线程的技术,目的是防止发送邮件的过程阻碍主网站程序的运行。

具体代码如下:

public bool SendEmail(out string message)
        {
            string str3;
            bool flag = false;
            message = string.Empty;
            this.MailMM.Priority = MailPriority.Normal;
            this.MailMM.BodyEncoding = Encoding.UTF8;
            this.MailMM.IsBodyHtml = this.IsBodyHtml;



  

//关于图片

AlternateView htmlView = null; try { htmlView = AlternateView.CreateAlternateViewFromString(StrMailContent,null, "text/html"); for (int i = 0; i < aboImgSrcList.Count; i++) { try { LinkedResource logo = new LinkedResource(aboImgSrcList[i], "image/jpeg"); logo.ContentId = "imgSrc" + (i + 1); htmlView.LinkedResources.Add(logo); } catch (Exception EX) { } } MailMM.AlternateViews.Add(htmlView);
//关于附件          
for (int i = 0; i < this.AttachmentsList.Count; i++) { string tempStr = this.AttachmentsList[i].ToString(); Attachment attach = new Attachment(tempStr); this.MailMM.Attachments.Add(attach); }
} catch (Exception) { } int count = 0; foreach (string str in this.arrMailTo.Keys) { try { this.MailMM.To.Add(new MailAddress(this.arrMailTo[str])); if (this.StrMailTitle != "") { this.MailMM.Subject = this.StrMailTitle; } this.MailMM.SubjectEncoding = Encoding.UTF8; if (this.MailMM.From == null) { this.MailMM.From = new MailAddress(this.StrSender, (this.StrSenderDesc == "") ? this.StrSender : this.StrSenderDesc, Encoding.UTF8); } SmtpClient client = new SmtpClient { DeliveryMethod = SmtpDeliveryMethod.Network, EnableSsl = false, Host = this.MailServer, Port = int.Parse(this.SmtpPort), Credentials = new NetworkCredential(this.StrSenderUser, this.StrSenderUserPass) }; client.Send(this.MailMM); MailMM.To.Clear(); flag = true; count++; } catch (SmtpException exception) { flag = false; message +="("+count+") "+DateTime.Now.ToString()+" "+ this.arrMailTo[str] + ": " + exception.Message + ";\r\n"; } catch (InvalidCastException exc) { flag = false; message += "(" + count + ") " + DateTime.Now.ToString() + " " + this.arrMailTo[str] + ": " + exc.Message + ";\r\n"; } catch (Exception ex) { flag = false; message += "(" + count + ") " + DateTime.Now.ToString() + " " + this.arrMailTo[str] + ": " + ex.Message + ";\r\n"; } } return flag; }

然后在global文件中Application_Start的方法内开启一下线程池,用于遍历邮箱的队列,如果队列中有要发的邮件,则自动调用发送邮件的代码进行邮件发送。

代码如下:

 

 1 protected void Application_Start(object sender, EventArgs e)
 2         {
 3             string basePath = AppDomain.CurrentDomain.BaseDirectory;
 4             //step 2: start a thread to scan email queue(send email)
 5             ThreadPool.QueueUserWorkItem((o) =>
 6             {
 7                 while (true)
 8                 {
 9                     try
10                     {
11                         if (EmailHelper.mailQueueLR.Count > 0)
12                         {
13                             lock (this)
14                             {
15                                 if (EmailHelper.mailQueueLR.Count > 0)
16                                 {
17                                     int tempInt = EmailHelper.mailQueueLR.Dequeue();
18                                     if (tempInt == null || tempInt == 0)
19                                     {
20                                     }
21                                     else
22                                     {
23                                       //此处为创建一个邮件的具体代码,根据实际情况编写
24                                      }
25                                         catch (Exception ex)
26                                         {
27                                             //this.AddMsg(exception.Message);
28                                             string str = ex.Message;
29                                             str = str + "str";
30 
31                                         }
32                                     }
33                                 }
34                             }
35                         }
36                         else
37                         {
38                             Thread.Sleep(1000);
39                         }
40                     }
41                     catch (InvalidOperationException ioex)
42                     {
43                         continue;
44                     }
45                     catch (Exception ex)
46                     {
47                         continue;
48                     }
49 
50                 }
51             }, basePath);
52         }
View Code

 实际开发中遇到的问题

1:在Ipad或者iphone设备中出现了,接收到的邮件只显示源代码的情况。

     原因:在发送邮件时,实际是发送了两份,一份源代码,一份可选内容,而在ipad中却只显示了源代码

    解决方法:把所有的HTML代码都放到可变视图(AlternateViews)中去,不再放到body里面,

2:在邮件显示时,出现了乱码的情况。

    原因:邮件内容编码格式不统一,例如:正文内容跟标题编码格式不统一

    解决方法:统一编码格式,所有字符串都转换成相同编码格式

 

推荐阅读