我与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);
}
如何更改它以从数据库获取邮件设置?
答案 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);