Friday 3 August 2012

Using C# to send authenticated email through Exchange 2010

problem :

Our Exchange 2010 environment requires that all users (with some exceptions to servers) authenticate before sending email, and that communication takes place over SSL using certificates.

I've found it somewhat difficult to achieve this, due to the following errors -

1. The Server response was: 5.7.1 Client does not have permissions to send as this sender
2. The remote certificate is invalid according to the validation procedure

solution :

1. The only way I can send from my mailbox is by giving another account (like a service account) 'Send As' permissions on it and specifying those credentials. My own credentials produce the above error.

2. When specifying the Host or Server (which is the Client Access Server in Exchange speak), you need to either use the host name that is included on its certificate, or include this line of code to ignore certificate errors -

ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

Thanks. Here is my method -
Jim

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

namespace Send_Email_BVCAS2010
{
    class Program
    {
        static void Main(string[] args)
        {
            SmtpClient smtpClient = new SmtpClient();
            NetworkCredential basicCredential = new NetworkCredential("domain\\user", "password");   // User with 'sendAs' permissions on the mailbox. Cannot use your own creds
            MailMessage message = new MailMessage();
            MailAddress fromAddress = new MailAddress("sender@domain.com.au");   // From this mailbox..

            smtpClient.Host = "CAS_Server_Name";
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = basicCredential;
            smtpClient.EnableSsl = true;

            message.From = fromAddress;
                          message.Subject = "test in c#";
            //Set IsBodyHtml to true means you can send HTML email.
            message.IsBodyHtml = true;
            message.Body = "<h1>Message BODY</h1>";
            message.To.Add("recipient@domain.com.au");

            try

            {
                ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
                smtpClient.Send(message);

            }
            catch (Exception ex)
            {
                //Error, could not send the message
                Console.WriteLine(ex.Message);
                Console.WriteLine("Finished");
                Console.ReadLine();
            }
        }
    }
}




No comments:

Post a Comment