Setting multiple SMTP settings in web.config?

前端 未结 8 1366
庸人自扰
庸人自扰 2020-12-01 00:42

I am building an app that needs to dynamically/programatically know of and use different SMTP settings when sending email.

I\'m used to using the system.net/mailSet

8条回答
  •  时光说笑
    2020-12-01 01:28

    Just pass in the relevant details when you are ready to send the mail, and store all of those settings in your app setttings of web.config.

    For example, create the different AppSettings (like "EmailUsername1", etc.) in web.config, and you will be able to call them completely separately as follows:

            System.Net.Mail.MailMessage mail = null;
            System.Net.Mail.SmtpClient smtp = null;
    
            mail = new System.Net.Mail.MailMessage();
    
            //set the addresses
            mail.From = new System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings["Email1"]);
            mail.To.Add("someone@example.com");
    
            mail.Subject = "The secret to the universe";
            mail.Body = "42";
    
            //send the message
            smtp = new System.Net.Mail.SmtpClient(System.Configuration.ConfigurationManager.AppSettings["YourSMTPServer"]);
    
            //to authenticate, set the username and password properites on the SmtpClient
            smtp.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["EmailUsername1"], System.Configuration.ConfigurationManager.AppSettings["EmailPassword1"]);
            smtp.UseDefaultCredentials = false;
            smtp.Port = System.Configuration.ConfigurationManager.AppSettings["EmailSMTPPort"];
            smtp.EnableSsl = false;
    
            smtp.Send(mail);
    

提交回复
热议问题