在不使用webconfig中的<mailsettings>的情况下通过hangfire发送电子邮件

时间:2016-11-13 09:47:27

标签: c# asp.net-mvc email hangfire

我与asp.net mvc 5 C#合作。 我想通过hangfire发送电子邮件而不从webconfing获取数据。 在webconfig中我有这段代码:

<mailSettings>
  <smtp from="email@site.com">
    <network host="host" port="25" userName="email@site.com" password="*****" enableSsl="false" defaultCredentials="false" />
  </smtp>
</mailSettings>

当我在Webconfig中使用时,一切正常。 但现在我想将电子邮件和密码存储在数据库中并从数据库中获取值。

这是.cs代码

 [AutomaticRetry(Attempts = 20)]
        public static void SendEmailToMember(Member obj,string Subject, string Details){        
        var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
                var engines = new ViewEngineCollection();
                engines.Add(new FileSystemRazorViewEngine(viewsPath));

                var emailService = new Postal.EmailService(engines);

                var ee = new SendEmailToMember
                {
                    To = obj.Email,
                    FullName = obj.FullName,
                    Subject=Subject,
                    Details = Details,
                    ViewName = "SendEmailToMember"
                };

                emailService.Send(ee);

}

如何更改它以从数据库获取邮件设置?

1 个答案:

答案 0 :(得分:1)

您可以使用SmtClient创建新的Postal.EmailService,导入System.Net.Mail命名空间并使用此代码

        MailMessage mail = new MailMessage();

        SmtpClient smtpServer = new SmtpClient("smtp.gmail.com"); //gmail smtp server
        smtpServer.Credentials = new System.Net.NetworkCredential("loginFromDB", "passwordFromDB");
        smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpServer..EnableSsl = false;
        smtpServer.Port = 587; // gmail works on this port

        mail.From = new MailAddress("yourMail@gmail.com");
        mail.To.Add("recepient@gmail.com");
        mail.Subject = "Hello from the other side";
        mail.Body = "your body";

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

        emailService.Send(email);