一个关于发邮件的类,可以模拟发送对smtp服务器或者是本地文件夹
1 namespace SportsStore.Domain.Concrete { 2 3 public class EmailSettings { 4 public string MailToAddress = "orders@example.com"; 5 public string MailFromAddress = "sportsstore@example.com"; 6 public bool UseSsl = true; 7 public string Username = "MySmtpUsername";//MailToAddress一样 8 public string Password = "MySmtpPassword"; 9 public string ServerName = "smtp.example.com"; 10 public int ServerPort = 587;//Gmail为587,其他一般为25 11 public bool WriteAsFile = false;//设为false邮件将发送到路径FileLoacation 12 public string FileLocation = @"c:\sports_store_emails"; 13 } 14 15 public class EmailOrderProcessor :IOrderProcessor { 16 private EmailSettings emailSettings; 17 18 public EmailOrderProcessor(EmailSettings settings) { 19 emailSettings = settings; 20 } 21 22 public void ProcessOrder(Cart cart, ShippingDetails shippingInfo) { 23 24 using (var smtpClient = new SmtpClient()) { 25 26 smtpClient.EnableSsl = emailSettings.UseSsl; 27 smtpClient.Host = emailSettings.ServerName; 28 smtpClient.Port = emailSettings.ServerPort; 29 smtpClient.UseDefaultCredentials = false; 30 smtpClient.Credentials 31 = new NetworkCredential(emailSettings.Username, emailSettings.Password); 32 if (emailSettings.WriteAsFile) { 33 smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; 34 smtpClient.PickupDirectoryLocation = emailSettings.FileLocation; 35 smtpClient.EnableSsl = false; 36 } 37 38 StringBuilder body = new StringBuilder() 39 .AppendLine("A new order has been submitted") 40 .AppendLine("---") 41 .AppendLine("Items:"); 42 43 foreach (var line in cart.Lines) { 44 var subtotal = line.Product.Price * line.Quantity; 45 body.AppendFormat("{0} x {1} (subtotal: {2:c}", line.Quantity, 46 line.Product.Name, 47 subtotal); 48 } 49 body.AppendFormat("Total order value: {0:c}", cart.ComputeTotalValue()) 50 .AppendLine("---") 51 .AppendLine("Ship to:") 52 .AppendLine(shippingInfo.Name) 53 .AppendLine(shippingInfo.Line1) 54 .AppendLine(shippingInfo.Line2 ?? "") 55 .AppendLine(shippingInfo.Line3 ?? "") 56 .AppendLine(shippingInfo.City) 57 .AppendLine(shippingInfo.State ?? "") 58 .AppendLine(shippingInfo.Country) 59 .AppendLine(shippingInfo.Zip) 60 .AppendLine("---") 61 .AppendFormat("Gift wrap: {0}", shippingInfo.GiftWrap ? "Yes" : "No"); 62 63 MailMessage mailMessage = new MailMessage( 64 emailSettings.MailFromAddress, // From 65 emailSettings.MailToAddress, // To 66 "New order submitted!", // Subject 67 body.ToString()); // Body 68 69 if (emailSettings.WriteAsFile) { 70 mailMessage.BodyEncoding = Encoding.ASCII; 71 } 72 73 smtpClient.Send(mailMessage); 74 } 75 } 76 } 77 }
posted on 2013-11-17 00:18 YEKEYISHUO 阅读(779) 评论(0) 编辑 收藏 举报