That's a very basic code,
It should work if everythings is correct, but it seems that the problem may be in checking the destination email if it really exists.
I have a pretty good function for that which get rid of most of the common errors by checking with regular expressions and mxrecords:
public static bool CheckEmail(String myContact,bool securesent)
{
string pattern = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex check = new Regex(pattern, RegexOptions.IgnorePatternWhitespace);
bool valid = false;
if (string.IsNullOrEmpty(myContact))
{
valid = false;
}
else
{
valid = check.IsMatch(myContact);
if (!valid)
{
CreateLogFiles Log = new CreateLogFiles();
Log.ErrorLog("C:/", "FORMAT Error : NAME=(" + name + ") \t ToAddress=(" + toMail + ")", "FORMATErrors.txt");
}
if (securesent)
{
try
{
string[] host = (myContact.Split('@'));
string hostname = host[1];
string[] MX = DnsMx.GetMXRecords(hostname);
IPHostEntry IPhst = Dns.GetHostEntry(MX[0]);
IPEndPoint endPt = new IPEndPoint(IPhst.AddressList[0], 25);
Socket s = new Socket(endPt.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
}
catch (Exception ex)
{
return false;
}
}
}
return valid;
}
After checking the email it's pretty much what you did, but you can still improve by sending it async. so that you can get error info from exchange server in case you are using one.
MailMessage mail = new MailMessage();
MailAddress toMA = new MailAddress("email@domain.com","NAME");
MailAddress FromMA;
FromMA = new MailAddress("email@domain.com","NAME");
mail.Headers.Add("Return-Path", "email@domain.com");
mail.ReplyTo = FromMA;
client.Credentials = new System.Net.NetworkCredential("USERLOGIN", "USERPWD");
mail.To.Add(toMA);
mail.From = FromMA;
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
mail.SubjectEncoding = Encoding.UTF8;
mail.Subject = subject;
mail.BodyEncoding = Encoding.UTF8;
mail.Body = body;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
if (securesent)
{
client.SendCompleted += new SendCompletedEventHandler(MailDeliveryComplete);
client.SendAsync(mail, mail.To[0].ToString());
}
else
{
client.Send(mail);
}
}
}
catch (Exception ex)
{
return ex.Message;
}