Setting multiple SMTP settings in web.config?

前端 未结 8 1363
庸人自扰
庸人自扰 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:19

    I had the same need and the marked answer worked for me.

    I made these changes in the

    web.config:

          
            
              
    // noreply, in my case - use your mail in the condition bellow ...

    Then, I have a thread that send the mail:

    SomePage.cs

    private bool SendMail(String From, String To, String Subject, String Html)
        {
            try
            {
                System.Net.Mail.SmtpClient SMTPSender = null;
    
                if (From.Split('@')[0] == "noreply")
                {
                    System.Net.Configuration.SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("mailSettings2/noreply");
                    SMTPSender = new System.Net.Mail.SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
                    SMTPSender.Credentials = new System.Net.NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
                    System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
                    Message.From = new System.Net.Mail.MailAddress(From);
    
                    Message.To.Add(To);
                    Message.Subject = Subject;
                    Message.Bcc.Add(Recipient);
                    Message.IsBodyHtml = true;
                    Message.Body = Html;
                    Message.BodyEncoding = Encoding.GetEncoding("ISO-8859-1");
                    Message.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1");
                    SMTPSender.Send(Message);
    
                }
                else
                {
                    SMTPSender = new System.Net.Mail.SmtpClient();
                    System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
                    Message.From = new System.Net.Mail.MailAddress(From);
    
                    SMTPSender.EnableSsl = SMTPSender.Port ==  || SMTPSender.Port == ;
    
                    Message.To.Add(To);
                    Message.Subject = Subject;
                    Message.Bcc.Add(Recipient);
                    Message.IsBodyHtml = true;
                    Message.Body = Html;
                    Message.BodyEncoding = Encoding.GetEncoding("ISO-8859-1");
                    Message.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1");
                    SMTPSender.Send(Message);
                }
            }
            catch (Exception Ex)
            {
                Logger.Error(Ex.Message, Ex.GetBaseException());
                return false;
            }
            return true;
        }
    

    Thank you =)

提交回复
热议问题