Search code examples
c#emailexchange-server

Sending Email through Microsoft Exchange Server


Okay, so I have this program which in essence acts as an email client for a company, it constructs the email for them and sends it out.

I've done everything on it, but when going to send the email, they get a Mailbox Unavailable. Accessed Denied - Invalid HELO Name

Interestingly though, I use the same username for the network credentials and the from part.

EDIT: Update code to what I'm now using... Now getting Failure sending mail error.

Here is my MailConst.cs class:

public class MailConst
{
    
    /*
     */

    public static string Username = "username";
    public static string Password = "password";
    public const string SmtpServer = "smtp.domain.co.uk";

    public static string From = Username + "@domain.co.uk";

}

and here is the use of these variables in my main class:

public static void SendMail(string recipient, string subject, string body, string[] attachments)
{
        

    SmtpClient smtpClient = new SmtpClient();
    NetworkCredential basicCredential = new NetworkCredential(MailConst.Username, MailConst.Password, MailConst.SmtpServer);
    MailMessage message = new MailMessage();
    MailAddress fromAddress = new MailAddress(MailConst.From);

    // setup up the host, increase the timeout to 5 minutes
    smtpClient.Host = MailConst.SmtpServer;
    smtpClient.UseDefaultCredentials = false;
    smtpClient.Credentials = basicCredential;
    smtpClient.Timeout = (60 * 5 * 1000);

    message.From = fromAddress;
    message.Subject = subject + " - " + DateTime.Now.Date.ToString().Split(' ')[0];
    message.IsBodyHtml = true;
    message.Body = body.Replace("\r\n", "<br>");
    message.To.Add(recipient);

    if (attachments != null)
    {
        foreach (string attachment in attachments)
        {
            message.Attachments.Add(new Attachment(attachment));
        }
    }
        
    smtpClient.Send(message);
}

Just as a side note. The program works when using my credentials, when going through my own server, just doesn't work when linking it to theirs.


Solution

  • In order to fix this problem I had to use the optional parameter Domain for the NetworkCredential

    My code now looks like this:

    NetworkCredential basicCredential = new NetworkCredential(MailConst.UserName, MailConst.Password, MailConst.Domain

    Where the MailConst.Domain is a string pointing to the Exchange domain.