我无法发送电子邮件 smtp 错误

Posted

技术标签:

【中文标题】我无法发送电子邮件 smtp 错误【英文标题】:i can't send email smtp error 【发布时间】:2016-08-24 14:58:47 【问题描述】:

我现在正在学习“Pro ASP.NET MVC 4 (Professional Apress)”,当我想编译我的项目时收到以下错误:

SmtpException 未被用户代码处理

“System.Net.Mail.SmtpException”类型的异常发生在 System.dll 但未在用户代码中处理 附加信息:发送邮件失败。

这是源代码:

using System.Net.Mail;
using System.Text;
using SportsStore.Domain.Abstract;
using SportsStore.Domain.Entities;
using System.Net;

namespace SportsStore.Domain.Concrete


public class EmailSettings

    public string MailToAddress = "abc@wp.pl";
    public string MailFromAddress = "abcd@wp.pl";
    public bool UseSsl = true;
    public string Username = "abcd@wp.pl";
    public string Password = "abcd12";
    public string ServerName = "smtp.wp.pl";
    public int ServerPort = 465;
    public bool WriteAsFile = false;
    public string FileLocation = @"c:\sports_store_emails";


public class EmailOrderProcessor : IOrderProcessor

    private EmailSettings emailSettings;

    public EmailOrderProcessor(EmailSettings settings)
    
        emailSettings = settings;
    

    public void ProcessOrder(Cart cart, ShippingDetails shippingInfo)
    

        using (var smtpClient = new SmtpClient())
        

            smtpClient.EnableSsl = emailSettings.UseSsl;
            smtpClient.Host = emailSettings.ServerName;
            smtpClient.Port = emailSettings.ServerPort;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials
                = new NetworkCredential(emailSettings.Username,
                      emailSettings.Password);

            if (emailSettings.WriteAsFile)
            
                smtpClient.DeliveryMethod
                    = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                smtpClient.PickupDirectoryLocation = emailSettings.FileLocation;
                smtpClient.EnableSsl = false;
            

            StringBuilder body = new StringBuilder()
                .AppendLine("Nowe zamówienie")
                .AppendLine("---")
                .AppendLine("Produkty:");

            foreach (var line in cart.Lines)
            
                var subtotal = line.Product.Price * line.Quantity;
                body.AppendFormat("0 x 1 (wartość: 2:c", line.Quantity,
                                  line.Product.Name,
                                  subtotal);
            

            body.AppendFormat("Wartość całkowita: 0:c", cart.ComputeTotalValue())
                .AppendLine("---")
                .AppendLine("Wysyłka dla:")
                .AppendLine(shippingInfo.Name)
                .AppendLine(shippingInfo.Line1)
                .AppendLine(shippingInfo.Line2 ?? "")
                .AppendLine(shippingInfo.Line3 ?? "")
                .AppendLine(shippingInfo.City)
                .AppendLine(shippingInfo.State ?? "")
                .AppendLine(shippingInfo.Country)
                .AppendLine(shippingInfo.Zip)
                .AppendLine("---")
                .AppendFormat("Pakowanie prezentu: 0",
                    shippingInfo.GiftWrap ? "Tak" : "Nie");

            MailMessage mailMessage = new MailMessage(
                                   emailSettings.MailFromAddress,   // od
                                   emailSettings.MailToAddress,     // do
                                   "Otrzymano nowe zamówienie!",          // temat
                                   body.ToString());                // treść

            if (emailSettings.WriteAsFile)
            
                mailMessage.BodyEncoding = Encoding.ASCII;
            

            smtpClient.Send(mailMessage);
        
    


任何想法如何解决这个问题?

这是摘录细节:

System.Net.Mail.SmtpException 未被用户代码处理 HResult=-2146233088 Message=发送邮件失败。源=系统 堆栈跟踪: 在 System.Net.Mail.SmtpClient.Send(MailMessage 消息) 在 SportsStore.Domain.Concrete.EmailOrderProcessor.ProcessOrder(购物车 购物车, ShippingDetails shippingInfo) 在 C:\Users\rafal\Desktop\Rozdzial07-11\SportsStore\SportsStore.Domain\Concrete\EmailOrderProcessor.cs:line 93 在 SportsStore.WebUI.Controllers.CartController.Checkout(Cart cart, ShippingDetails shippingDetails) 中 C:\Users\rafal\Desktop\Rozdzial07-11\SportsStore\SportsStore.WebUI\Controllers\CartController.cs:line 39 在 lambda_method(闭包,ControllerBase,对象 []) 在 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase 控制器,Object[] 参数) 在 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext 控制器上下文,IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 参数) 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass81.b__7(IAsyncResult _) 在 System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() 在 System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult,对象标签) 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult 异步结果) 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.c__DisplayClass37.c__DisplayClass39.b__33() 在 System.Web.Mvc.Async.AsyncControllerActionInvoker.c__DisplayClass4f.b__49() 内部异常: H结果=-2147024893 消息=找不到路径“c:\sports_store_emails\c4734a39-5267-4199-bb29-f28542b3c5ac.eml”的一部分。 源=mscorlib 堆栈跟踪: 在 System.IO.__Error.WinIOError(Int32 错误代码,字符串可能全路径) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize,FileOptions 选项,SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean 检查主机) 在 System.IO.FileStream..ctor(字符串路径、FileMode 模式、FileAccess 访问、FileShare 共享、Int32 bufferSize、FileOptions 选项,字符串 msgPath,布尔 bFromProxy) 在 System.IO.FileStream..ctor(字符串路径,FileMode 模式) 在 System.Net.Mail.SmtpClient.GetFileMailWriter(字符串pickupDirectory) 在 System.Net.Mail.SmtpClient.Send(MailMessage 消息) 内部异常:

这 2 个警告:

    警告

警告 CS0618 'FormsAuthentication.Authenticate(string, string)' 是 过时:'推荐的替代方法是使用会员 API, 例如 Membership.ValidateUser。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=252463.' SportsStore.WebUI C:\Users\rafal\Desktop\Rozdzial07-11\SportsStore\SportsStore.WebUI\Infrastructure\Concrete\FormsAuthProvider.cs 10 活动

    警告

警告 发现相同版本的不同版本之间存在冲突 无法解析的依赖程序集。这些参考 当日志详细程度设置为时,冲突会在构建日志中列出 详细的。 SportsStore.WebUI

如何解决这个问题?

【问题讨论】:

查看内部异常Could not find a part of the path 'c:\sports_store_emails\c4734a39-5267-4199-bb29-f28542b3c5ac.eml'. 检查应用程序池的权限——它可以读/写到那个位置吗? 正确检查路径!! 谢谢是权限问题 【参考方案1】:
//Create Mail body
string Emails = MailId;
string file = Server.MapPath("~/Mail.html");
//Generate Mail Body
string mailbody = "Hi"+" " +Emails;
//Whom to send email
 string to = Emails;
//Who is sending mail
string from = "Sender_Mail_Id";
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Auto Response Email";
msg.Body = mailbody;
msg.BodyEncoding = Encoding.UTF8;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.UseDefaultCredentials = false;
System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential("User_EMailId", "Password");
client.EnableSsl = true;
client.UseDefaultCredentials = true;
client.Credentials = basicCredential;

【讨论】:

以上是关于我无法发送电子邮件 smtp 错误的主要内容,如果未能解决你的问题,请参考以下文章

错误 SMTP 无法从 gmail 发送电子邮件

无法在 codeigniter 中从 gmail 发送电子邮件,SMTP 身份验证错误

通过 SMTP 使用 AWS SES 发送电子邮件,错误 421

SMTP Connect() 失败。邮件未发送。邮件程序错误:SMTP Connect() 失败

发送 AUTH LOGIN 命令失败。错误:无法使用 PHP SMTP 发送电子邮件。您的服务器可能未配置为使用此方法发送邮件

我无法使用 gmail SMTP 通过 swift 邮件发送邮件