【问题标题】:ASP.NET Exchange Server Send Email C#ASP.NET Exchange 服务器发送电子邮件 C#
【发布时间】:2011-12-03 10:52:51
【问题描述】:

好的,当我输入这个时,我注意到可能涵盖相同问题的不同主题。我访问了他们中的大多数,发现与我的要求没有直接关系,所以我请求耐心。

无论如何,我正在使用 VS2010 创建一个 ASP.NET Web 应用程序。我正在尝试使用代码通过 smtp 发送电子邮件:

        MailMessage mailMsg = new MailMessage();

        mailMsg.From = new MailAddress(fromEmail);
        mailMsg.To.Add(toEmail);
        mailMsg.Subject = emailSubj.ToString().Trim();
        mailMsg.Body = msgBody.ToString().Trim();
        SmtpClient smtpClient = new SmtpClient();
        smtpClient.Send(mailMsg);

但每次我得到以下异常(SMTPException 和 innerException 说{"Unable to connect to the remote server"}

我还在 web.config 中定义了以下内容:

<system.net>
  <mailSettings>
    <smtp>
      <network host="company.com"/>
    </smtp>
  </mailSettings>
</system.net>

我要做的是在提交带有请求 ID 的表单后发送一封电子邮件,以便可以通过其他页面访问它(除邮件之外的所有作品)。在我们使用 Exchange 服务器的公司中,当我转到我的联系人属性时,我得到 smtp:emailaddress@company.com

那么这里要做什么呢?我已经检查了Web Services ExchangeServiceBinding,但无法真正找到可以直接帮助我的东西(因此感谢任何链接)

非常感谢,期待阅读您的回复:)

【问题讨论】:

    标签: c# asp.net exchange-server


    【解决方案1】:

    试试这个独立的 C# 应用程序,看看主机名是否有效。否则,您需要联系管理员以获取正确的地址。

          /// <summary>
          ///Method to Send an Email informing interested parties about the status of data extraction. 
          /// INPUTS : int iProcessIsSuccess : int informing about the success of the process. -1 means failure, 0 means partial success, 1 means success. 
          ///          string szLogDataToBeSent :  Log data to be sent incase process not successful.
          /// OUTPUTS : bool. True if success, else false.
          /// </summary>
          public bool SendEmailNotification(string szEmailAddressFileName, int iProcessIsSuccess, string szLogDataToBeSent)
          {
             bool bSuccess = false;
    
             //the the SMTP host.
             SmtpClient client = new SmtpClient();
    
             //SMTP Server
             client.Host = CommonVariables.EMAIL_SMTP_SERVER;
    
             //SMTP Credentials
             client.Credentials = new NetworkCredential(CommonVariables.EMAIL_USERNAME, CommonVariables.EMAIL_PASSWORD);
    
             //Creating a new mail.
             MailMessage mail = new MailMessage();
    
             //Filling 'From' Tab.
             mail.From = new MailAddress(CommonVariables.EMAIL_SENDERS_ADDRESS, CommonVariables.EMAIL_SENDERS_NAME);
    
             //Filling 'To' tab.
             List<EmailAddress> EmailAddressList = new List<EmailAddress>();
             try
             {
                using (System.IO.FileStream fs = new FileStream(szEmailAddressFileName, FileMode.Open))
                {
                   XmlSerializer xs = new XmlSerializer(typeof(List<EmailAddress>));
                    EmailAddressList = xs.Deserialize(fs) as List<EmailAddress>;
                }
    
                foreach (EmailAddress addr in EmailAddressList)
                {
                   mail.To.Add(addr.RecepientEmailAddress);
                }
             }
             catch(Exception Ex)
             {
                mail.To.Add("DefautEmailId@company.com");
             }
    
             //Filling mail body.
             string szMailBody = "";
             string szMailSubject = "";
    
             if (1 == iProcessIsSuccess) //Success
             {
                szMailSubject = String.Format(CommonVariables.EMAIL_SUBJECT_BOILER_PLATE, "a SUCCESS");
                szMailBody = String.Format(CommonVariables.EMAIL_BODY_BOILER_PLATE, DateTime.UtcNow.ToString(), Environment.MachineName);
                szMailBody += "\r\n" + szMailSubject + "\r\n";
    
             }
             else if (0 == iProcessIsSuccess) //Partially Success
             {
                szMailSubject = String.Format(CommonVariables.EMAIL_SUBJECT_BOILER_PLATE, "a PARTIAL SUCCESS"); ;
                szMailBody = String.Format(CommonVariables.EMAIL_BODY_BOILER_PLATE, DateTime.UtcNow.ToString(), Environment.MachineName);
                szMailBody += "\r\n"+ szMailSubject + "\r\n";
                szMailBody += "\r\n" + "The Log data is as follows:\r\n";
                szMailBody += szLogDataToBeSent;
                mail.Priority = MailPriority.High;
             }
             else //Failed
             {
                szMailSubject = String.Format(CommonVariables.EMAIL_SUBJECT_BOILER_PLATE, "a FAILURE"); ;
                szMailBody = String.Format(CommonVariables.EMAIL_BODY_BOILER_PLATE, DateTime.UtcNow.ToString(), Environment.MachineName);
                szMailBody += "\r\n" + szMailSubject + "\r\n";
                szMailBody += "\r\n" + "The Log data is as follows:\r\n";
                szMailBody += szLogDataToBeSent;
                mail.Priority = MailPriority.High;
             }
    
             mail.Body = szMailBody;
    
             mail.Subject = szMailSubject;
    
             //Send Email.
             try
             {
                client.Send(mail);
                bSuccess = true;
             }
             catch (Exception Ex)
             {
                bSuccess = false;
             }
    
             // Clean up.
             mail.Dispose();
    
    
             return bSuccess;
    
          }
    
       }
    

    【讨论】:

      【解决方案2】:

      与您的系统管理员交谈并获取您需要配置的 Exchange Server 的名称。

      【讨论】:

      • 您应该检查这些设置并提供正确的主机名值 -
      • 其实我在源码里找到了所有的设置。缺点是它们是用 Vb 而不是 C# 编写的 :((((
      【解决方案3】:

      有时 smtp 服务器与您所看到的不同。 例如: 我的电子邮件是 myemployee@mycompany.com, 我实际的 smtp 服务器是 server1.mail.mycompany.com、server2.mail.mycompany.com 您必须向管理员询问此服务器名称

      然后询问您的用户是否在 AD 上定义,是否需要对每个 smtp 发送进行身份验证?

      您的交换主机是否使用 SMTP over TLS ? AFAIK 一些交换管理员声明使用 SMTP over SSL 或 TLS。您可以通过获取其电子邮件的当前 Exchange/Windows 证书来查看有关使用 SMTP over SSL 或 TLS 发送的 MSDN 文档。

      【讨论】:

      • 尝试了上面的解决方案,但它没有因为一些尴尬的错误而编译...我刚刚获得了对我们源代码的访问权限,所以我要去那里寻找有关交换服务器的详细信息
      【解决方案4】:
            string _SMTP = WebConfigurationManager.AppSettings["SMTP"];
            Int32 _Port = Convert.ToInt16(WebConfigurationManager.AppSettings["Port"]);
            string _SMTPCredentialName = WebConfigurationManager.AppSettings["SMTPCredentialName"];
            string _SMTPCredentialPassword = WebConfigurationManager.AppSettings["SMTPCredentialPassword"];
            string _Body = null;
      
              System.Net.Mail.MailMessage _MailMessage = new System.Net.Mail.MailMessage();
              try
              {
                  _MailMessage.To.Add(_RegUserEmail);
                  _MailMessage.From = new System.Net.Mail.MailAddress(_FromEmail, _FromName);
                  _MailMessage.Subject = _Subject;
                  _Body = ReadTemplateRegistration(_RegisterName, _RegUserName, _RegUserEmail, _Pass, _Path);
                  _MailMessage.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");
      
                  AlternateView plainView = AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(_Body, "<(.|\\n)*?>", string.Empty), null, "text/plain");
                  AlternateView htmlView = AlternateView.CreateAlternateViewFromString(_Body, null, "text/html");
      
                  _MailMessage.AlternateViews.Add(plainView);
                  _MailMessage.AlternateViews.Add(htmlView);
      
                  System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(_SMTP, _Port);
      
                  System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential(_SMTPCredentialName, _SMTPCredentialPassword);
      
                  mailClient.UseDefaultCredentials = false;
      
                  mailClient.Credentials = basicAuthenticationInfo;
      
                  _MailMessage.IsBodyHtml = true;
      
                  mailClient.Send(_MailMessage);
              }
              catch (Exception ex)
              {
      
                  return "ERROR" + ex.ToString();
              }
      

      这是使用 C# 发送电子邮件的最佳方法,您可以在所有正在进行的电子邮件系统中使用此方法,包括 Exchange 服务器、pop3、smtp、Gmail、Hotmail Yahoo 等。

      【讨论】:

        猜你喜欢
        • 2017-07-28
        • 1970-01-01
        • 2016-12-18
        • 2011-04-18
        • 1970-01-01
        • 2015-11-08
        • 2012-07-27
        • 2013-09-06
        • 1970-01-01
        相关资源
        最近更新 更多