2012-11-21 42 views
1

我試圖創建一個函數,使用時將電子郵件發送到目標地址。使用C#.Net錯誤發送電子郵件5.7.1

我的電子郵件型號:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Net; 
using System.Net.Mail; 
using System.Security; 

namespace myspecial.net.Models 
{ 
    public class EmailModel 
    { 
     // Sender email and recipient email 
     public MailAddress Sender { get; set; } 
     public IEnumerable<MailAddress> Recipient { get; set; } 
     // Subject and message 
     public String Subject { get; set; } 
     public String Body { get; set; } 
     // Attachment Files 
     public String AttachmentPath { get; set; } 
     // Login Information 
     public String UserName { get; set; } 
     public String Password { get; set; } 
     // Simple Mail Transfer Protocol (SMTP) provider and port 
     public String SmtpServer { get; set; } 
     public Int32 SMTPport { get; set; } 
     // Post Office Protocol (POP) version 3 provider and port 
     public String POP3Server { get; set; } 
     public Int32 POP3port { get; set; } 
     // Secure Sockets Layer 
     public Boolean SSL { get; set; } 
    } 
} 

我的控制器:

/// <summary> 
/// E-Mail's to the address. Before using this function fill the email model. 
/// </summary> 
public void Email(EmailModel mailer) 
{ 
    MailMessage mail = new MailMessage(); 
    // Standart required mail information 
    mail.From = mailer.Sender; 
    mail.Sender = mailer.Sender; 
    // Recipients 
    foreach (MailAddress rcpnt in mailer.Recipient.ToList()) 
    { mail.To.Add(rcpnt); } 
    // Subject 
    mail.Subject = mailer.Subject; 
    // Body 
    mail.Body = mailer.Body; 
    // Optional Attachment 
    if (mailer.AttachmentPath != null || mailer.AttachmentPath.Trim() != "") 
    { 
     System.Net.Mail.Attachment attachment; 
     attachment = new System.Net.Mail.Attachment(mailer.AttachmentPath.Trim()); 
     mail.Attachments.Add(attachment); 
    } 
    // Important (Simple Mail Transfer Protocol) 
    SmtpClient SmtpServer = new SmtpClient(mailer.SmtpServer,mailer.SMTPport); 
    SmtpServer.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; 
    SmtpServer.Credentials = new System.Net.NetworkCredential(mailer.UserName, mailer.Password, mailer.SmtpServer); 
    SmtpServer.Port = mailer.SMTPport; 
    SmtpServer.EnableSsl = mailer.SSL; 
    ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; 
    // Send Mail 
    SmtpServer.Send(mail); 
} 

我如何使用它:

 // Send as mail 
     EmailModel mail = new EmailModel(); 
     // Mail addresses to send 
     MailAddress[] addressler = new MailAddress[] { new MailAddress("berkeryuc[email protected]") }; 
     // Options here 
     mail.SMTPport = 465; // Port // 465 // 26 // 25 // 366 // 587 
     mail.SmtpServer = "smtp.gmail.com"; // Server 
     mail.UserName = "[email protected]"; // UserName 
     mail.Password = "**********"; // Password 
     mail.SSL = true; // Secure Sockets Layer 
     // Mail 
     mail.Sender = new MailAddress("[email protected]"); // Sender (From) 
     mail.Recipient = addressler; // Recipient (To) 
     mail.Subject = "Some subject here.."; 
     mail.Body = "Some blabla bla blablabla blabla here..."; 
     // Optional Attachment // Attach excel file. 
     mail.AttachmentPath = ExportToExcelForMail(id).ToString(); 
     Email(mail); 

在我的web項目中創建一個報告的Excel文件,並想送它給我自己附上一封電子郵件。我不知道什麼是錯的或者什麼,我在這裏失蹤。一切似乎有效的給我,但我仍收到此錯誤:

MY ERROR IMAGE

堆棧跟蹤:

System.Net.Mail.SmtpFailedRecipientException was unhandled by user code 
    Message=Posta kutusu kullanılamıyor. Sunucu yanıtı şöyleydi: 5.7.1 <[email protected]> Access to <[email protected]> not allowed 
    Source=System 
    FailedRecipient=<[email protected]> 
    StackTrace: 
     konum: System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception) 
     konum: System.Net.Mail.SmtpClient.Send(MailMessage message) 
     konum: blabla.net.Controllers.OtelFormsController.Email(EmailModel mailer) D:\bla\bla\blabla.net\blabla.net\Controllers\OtelFormsController.cs içinde: satır 753 
     konum: blabla.net.Controllers.OtelFormsController.Close(Int32 id) D:\bla\bla\blabla.net\blabla.net\Controllers\OtelFormsController.cs içinde: satır 691 
     konum: lambda_method(Closure , ControllerBase , Object[]) 
     konum: System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) 
     konum: System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) 
     konum: System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) 
     konum: System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() 
     konum: System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) 
    InnerException: 

所以我是什麼?在這裏失蹤?怎麼了?我如何解決這個問題?

+3

您的郵件服務器拒絕發送消息。這可能表明密碼錯誤。 – SLaks

+0

這不一定是一個編程問題。這很可能是服務器上的配置/重播權限問題。它可能更適合在ServerFault.com。我們有時會在一個新的SMTP服務器設置時看到這種情況,因爲默認情況下它已被鎖定。我們必須明確允許某些用戶/服務器通過我們的SMTP服務器中繼SMTP郵件。 – David

+0

但我的密碼總是很好,即時嘗試郵寄編程方式所以問題適合在這裏。 –

回答

1

您可以使用下面的代碼:

/// <summary> 
    /// Sends mail with authentification 
    /// </summary> 
    /// <param name="recipients"></param> 
    /// <param name="from"></param> 
    /// <param name="subject"></param> 
    /// <param name="body"></param> 
    /// <param name="isHTMLbody"></param> 
    /// <param name="SMTPhost"></param> 
    /// <param name="priority"></param> 
    /// <param name="credentials"></param> 
    /// <param name="port"></param> 
    /// <param name="enableSsl"></param> 
    static void SendMailWithAuthentication(List<string> recipients, string from, string subject, string body, bool isHTMLbody, 
     string SMTPhost, System.Net.Mail.MailPriority priority, System.Net.NetworkCredential credentials, int? port, bool enableSsl) 
    { 
     System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); 
     foreach (string recipient in recipients) 
     { 
      message.To.Add(recipient); 
     } 
     message.SubjectEncoding = Encoding.UTF8; 
     message.BodyEncoding = Encoding.UTF8; 
     message.Subject = subject; 
     message.From = new System.Net.Mail.MailAddress(from); 
     message.IsBodyHtml = isHTMLbody; 
     message.Body = body; 
     message.Priority = priority; 
     System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(); 
     client.Credentials = credentials; 
     client.Host = SMTPhost; 
     if (port != null) 
     { 
      client.Port = (int)port; 
     } 
     client.EnableSsl = enableSsl; 
     client.Send(message); 
     message.Dispose(); 
    } 

而且這是你應該如何使用它的Gmail:

 string subject = "my subject"; 
     string body = "my html body"; 
     int port = 587; 
     string SMTPhost = "smtp.gmail.com"; 
     string sender = "[email protected]"; 
     System.Net.Mail.MailPriority mPriority = System.Net.Mail.MailPriority.Low;   
     List<string> recipients = new List<string>(){"[email protected]"}; 
     bool enableSSL = true; 
     System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("UserName","Password"); 
     SendMailWithAuthentication(recipients, sender, subject, body, true, 
      SMTPhost, 
      mPriority, credentials, 
      enableSSL); 
+0

希望添加附件不會吹這個。 –

+0

試試吧。此代碼每天都使用100%。如果你會有任何一種錯誤,那麼你應該看看你的服務器/域配置。 –

+0

正如我確信你的代碼完美工作,我也在'message.Priority = priority;'之後添加了附件。感謝您的解決方案。這段代碼也證明了DavidStratton對這個問題的誤解。它由髒編碼而不是服務器引起。我並不是說這對他意味着什麼。我只是想遏制誤導。 –