简体   繁体   English

ASP.NET Exchange Server发送电子邮件C#

[英]ASP.NET Exchange Server Send Email C#

Ok, as soon as I typed this I noticed the variant topics that may cover the same question. 好的,当我键入此内容时,我注意到可能涵盖相同问题的各种主题。 I visited most of them and found no direct relation to what I am asking, so I ask for patience. 我拜访了其中大多数人,发现与我要问的内容没有直接关系,因此我要耐心等待。

Anyway, I am creating an ASP.NET web application using VS2010. 无论如何,我正在使用VS2010创建一个ASP.NET Web应用程序。 I am trying to send an email via smtp using the code: 我正在尝试使用代码通过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);

but each time i get the following exception (SMTPException and innerException says {"Unable to connect to the remote server"} 但是每次我收到以下异常(SMTPException和innerException表示{"Unable to connect to the remote server"}

I also defined the following in the web.config: 我还在web.config中定义了以下内容:

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

What I am trying to do is to send an email once a form is submitted with the request ID so that it could be accessed via other pages (all the works except for the mail). 我想做的是一旦提交带有请求ID的表单,就发送一封电子邮件,以便可以通过其他页面(除邮件以外的所有作品)进行访问。 In the company we using Exchange server and when I go to my contact properties I get smtp:emailaddress@company.com 在公司中,我们使用Exchange服务器,当我进入联系方式时,我会收到smtp:emailaddress@company.com

So what is to be done here? 那么在这里该怎么办? I've checked Web Services ExchangeServiceBinding but couldn't really find directly something to help me (so any links appreciated) 我已经检查过Web Services ExchangeServiceBinding但找不到真正可以直接帮助我的东西(因此感谢任何链接)

Thanks a lot, and look forward to reading your replies :) 非常感谢,并期待阅读您的回复:)

Try this standalone C# application and see if the host name works. 试试这个独立的C#应用​​程序,看看主机名是否有效。 Else you will need to contact the admin for the correct address. 否则,您需要联系管理员以获取正确的地址。

      /// <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;

      }

   }

与系统管理员联系,获取需要配置的Exchange Server的名称。

Sometimes smtp servers is different from you are looking at. 有时smtp服务器与您正在查看的服务器不同。 for eg: my email is myemployee@mycompany.com, my actual smtp server is server1.mail.mycompany.com, server2.mail.mycompany.com This server name you have to ask to your admin 例如:我的电子邮件是myemployee@mycompany.com,我的实际smtp服务器是server1.mail.mycompany.com,server2.mail.mycompany.com您必须向管理员询问的服务器名称

After that ask that your user if defined on AD or not, and is it requires authentication for each smtp send? 之后,询问您的用户是否在AD上定义,并且是否需要对每个smtp发送进行身份验证?

Are your exchange host using SMTP over TLS ? 您的交换主机是否在TLS上使用SMTP? AFAIK some exchange admin declare using SMTP over SSL or TLS. AFAIK一些交换管理员声明通过SSL或TLS使用SMTP。 You can see MSDN documentation about sending using SMTP over SSL or TLS by getting current exchange/windows certificate for its email. 您可以通过获取其电子邮件的最新Exchange / Windows证书来查看有关通过SSL或TLS使用SMTP发送的MSDN文档。

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

This is the best method for sending email using C#, you can use this method all the on going email system including exchange server, pop3, smtp , Gmail, Hotmail Yahoo etc. 这是使用C#发送电子邮件的最佳方法,您可以在所有正在进行的电子邮件系统中使用此方法,包括交换服务器,pop3,smtp,Gmail,Hotmail Yahoo等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM