简体   繁体   中英

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. I am trying to send an email via smtp using the code:

        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"}

I also defined the following in the 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). In the company we using Exchange server and when I go to my contact properties I get 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)

Thanks a lot, and look forward to reading your replies :)

Try this standalone C# application and see if the host name works. 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. 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

After that ask that your user if defined on AD or not, and is it requires authentication for each smtp send?

Are your exchange host using SMTP over TLS ? AFAIK some exchange admin declare using SMTP over SSL or TLS. You can see MSDN documentation about sending using SMTP over SSL or TLS by getting current exchange/windows certificate for its email.

      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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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