Marwa Almahmoud Marwa Almahmoud - 27 days ago 13
C# Question

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@site.com">
<network host="host" port="25" userName="email@site.com" 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?

mww mww
Answer

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("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);