Marwa Almahmoud
Marwa Almahmoud

Reputation: 43

Send Email by hangfire without using <mailSettings> in webconfig

I worked with asp.net mvc 5 C#. I want to send email by hangfire without get data from webconfing. In webconfig I have this code:

<mailSettings>
  <smtp from="[email protected]">
    <network host="host" port="25" userName="[email protected]" password="*****" enableSsl="false" defaultCredentials="false" />
  </smtp>
</mailSettings>

when I use in Webconfig ,everything works correctly. But now I want to store email and password in database and get the value from database.

this is .cs code

 [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);

}

How I can change it to get mail settings from database?

Upvotes: 0

Views: 867

Answers (1)

M. Wiśnicki
M. Wiśnicki

Reputation: 6203

You can use SmtClient for create new Postal.EmailService, Import the System.Net.Mail namespace and use this code

        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("[email protected]");
        mail.To.Add("[email protected]");
        mail.Subject = "Hello from the other side";
        mail.Body = "your body";

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

        emailService.Send(email);

Upvotes: 1

Related Questions