【问题标题】:How to Set SMTP Client in POSTAL MVC not in WEB.Config如何在 POSTAL MVC 中而不是在 WEB.Config 中设置 SMTP 客户端
【发布时间】:2015-06-15 04:42:55
【问题描述】:

在我的项目中使用 POSTAL MVC 时遇到问题。我的托管服务公司要求我在代码中设置 smtp 客户端配置,而不是在 Web 配置中。

怎么做?

希望有人能给我解决办法

谢谢。

【问题讨论】:

    标签: c# asp.net-mvc-4 postal asp.net-mail


    【解决方案1】:

    我遇到了同样的问题。官方邮政文档中没有参考,也没有操作方法。 所以这里有一个:

    1. 使用自定义配置创建 SmtpClient 实例
    2. 使用带有 2 个参数(ViewEngineCollection、Func «SmtpClient»)的构造函数创建一个 Postal.EmailService 实例
    3. 现在您可以通过调用 emailService 使用自定义 SmtpClient 配置发送电子邮件。

    这里有一个完整的示例代码:

    dynamic email = new Email("Example");
    email.To = "webninja@example.com";
    email.FunnyLink = DB.GetRandomLolcatLink();
    
    SmtpClient client = new SmtpClient("mail.domain.com");
    client.UseDefaultCredentials = false;
    client.Credentials = new NetworkCredential("user@domain.pt", "somepassword");
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.Port = 25;
    client.EnableSsl = false;
    
    Postal.EmailService emailService = new Postal.EmailService(new ViewEngineCollection(), () => client);
    
    emailService.Send(email);
    

    【讨论】:

    • ViewEngineCollection 不是该 ctor 的有效参数,您无需解释它应该是什么。
    • 不知道ctor是什么意思?我有上面的代码在 MVC 5 控制器类上工作
    • ctor 是众所周知的构造函数缩写。而且,我很抱歉,我不知道为什么它之前不接受它,但现在它接受了。你只是缺少一个new,我已经为你添加了。
    • 我的错。我想我从来没有见过这个缩写。感谢您的编辑。
    • EmailService emaiService = new EmailService(ViewEngines.Engines, () => client);emaiService.SendAsync(email);
    【解决方案2】:

    添加到拉斐尔的答案。如果你使用

    Postal.EmailService emailService = new Postal.EmailService(new ViewEngineCollection(), () => client);
    

    您可能会收到此错误:Email view not found for [name for he email template]. Locations searched,因为new Postal.EmailService(new ViewEngineCollection(), () => client) 创建了带有空视图引擎的 emailService。使用ViewEngines.Engines 代替new ViewEngineCollection()(如@Houssam Hamdan 在上面的评论中所建议的那样)使用剃刀视图引擎。

    整行:

    Postal.EmailService emailService = new Postal.EmailService(ViewEngines.Engines, () => client);
    

    【讨论】:

      猜你喜欢
      • 2013-10-14
      • 2011-05-20
      • 2019-03-17
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      相关资源
      最近更新 更多