Sending Email with C# - Doesn't work, but no error thrown
as the topic title suggests, I am trying to send email from my C# application and i'm running into a little bit of trouble.
I wrote the function below in order to make it easier to send mail from my app, but i believe there must be a problem somewhere and I just can't see it. Perhaps it's the "Can't see the forest for the trees" scenario.
The problem occurs when I try to send email via SMTP. The page just seems to time out, with no error message, at all.. LocalPickup works, as does specifying a pickup directory, but in this instance I need to use SMTP.
In this case, my website is located on my home development server (running windows server 2003) and my SMTP server is a remote dedicated box running CentOS Linux with Qmail.
I've included the function I wrote, and just to answer any questions.. Yes, the SMTP port on this server is definately 26 ;)
/// <summary>
/// Sends an email
/// </summary>
/// <param name="To">Addresses to send the email to, comma seperated</param>
/// <param name="subject">Subject of the email</param>
/// <param name="emailBody">Content of the email</param>
/// <param name="cc">CC addresses, comma seperated [Optional]</param>
/// <param name="Bcc">BCC addresses, comma seperated [Optional]</param>
/// <param name="client">How to send mail, choices: iis, network, directory. [Optional] Defaults to iis</param>
/// <returns></returns>
public bool sendMail(string To, string subject, string emailBody, string from, string cc = "", string Bcc = "", string client = "network", bool html = true)
{
// Create a mailMessage object
MailMessage objEmail = new MailMessage();
objEmail.From = new MailAddress(from);
// Split email addresses by comma
string[] emailTo = To.Split(',');
foreach (string address in emailTo)
{
// Add these to the "To" address
objEmail.To.Add(address);
}
// Check for CC addresses
if (cc != "")
{
string[] emailCC = cc.Split(',');
foreach (string addressCC in emailCC)
{
objEmail.CC.Add(addressCC);
}
}
// Check for Bcc addresses
if (Bcc != "")
{
string[] emailBCC = Bcc.Split(',');
foreach (string addressBCC in emailBCC)
{
objEmail.Bcc.Add(addressBCC);
}
}
// Set the subject.
objEmail.Subject = subject;
// Set the email body
objEmail.Body = emailBody;
// Set up the SMTP client
SmtpClient server = new SmtpClient();
switch (client)
{
case "iis":
server.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
break;
case "network":
server.DeliveryMethod = SmtpDeliveryMethod.Network;
NetworkCredential credentials = new NetworkCredential("SmtpUserName", "SmtpPassword");
server.Host = "SmtpHost";
server.Port = 26;
server.Credentials = credentials;
break;
case "directory":
server.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
server.PickupDirectoryLocation = "c:\\mailpickup";
break;
default:
throw new Exception("Invalid delivery method specified, cannot continue!");
}
if (html)
{
// As the email is HTML, we need to strip out all tags for the plaintext version of the email.
string s = emailBody;
s = Regex.Replace(s, "<.*?>", string.Empty);
s = Regex.Replace(s, "<script.*?</script>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
AlternateView plainText = AlternateView.CreateAlternateViewFromString(s, null, MediaTypeNames.Text.Plain);
objEmail.AlternateViews.Add(plainText);
AlternateView rich = AlternateView.CreateAlternateViewFromString(emailBody, null, MediaTypeNames.Text.Html);
objEmail.AlternateViews.Add(rich);
}
try
{
server.Send(objEmail);
return true;
}
catch(Exception ex)
{
throw new Exception(ex.ToString());
}
As I said, the page just hangs completely after about 60 seconds, with no error mess开发者_JAVA技巧age to be seen.
Thanks in advance,
Dave
Addition: - This is how I am calling sendMail()
webMail sendConfirmation = new webMail();
fileSystem fs = new fileSystem();
siteSettings setting = new siteSettings();
string mailBody = fs.file_get_contents("http://myurl.com/mymessage.html");
// Run any replaces.
mailBody = mailBody.Replace("{EMAIL_TITLE}", "Your account requires confirmation");
mailBody = mailBody.Replace("{U_FNAME}", u_forename);
mailBody = mailBody.Replace("{REG_URL_STRING}", setting.confirmUrl);
sendConfirmation.sendMail(u_emailAddress, "Your account requires confirmation", mailBody, setting.siteEmail);
you can try to check for error:
SmtpClient smtp = new SmtpClient();
smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);
smtp.Send(msgMail);
void smtp_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Cancelled == true || e.Error != null)
{
throw new Exception(e.Cancelled ? "EMail sedning was canceled." : "Error: " + e.Error.ToString());
}
can't find a valid MX for rcpt domain typically means a valid email address or email domain cannot be found to relay the email to: I would take a look at the array of "to" email addresses being split to ensure each one is valid/from a valid domain. Possibly send a single test to each "to" email address so you can verify if this is an smtp server issue.
Another possiblity is localhost/iis permissions for relaying to another smtp server "??"
My test code for single address tests:
public void Send(string from, string to,string smtpServer, int smtpPort,string username, string password)
{
try
{
using (MailMessage mm = new MailMessage())
{
SmtpClient sc = new SmtpClient();
mm.From = new MailAddress(from, "Test");
mm.To.Add(new MailAddress(to));
mm.IsBodyHtml = true;
mm.Subject = "Test Message";
mm.Body = "This is a test email message from csharp";
mm.BodyEncoding = System.Text.Encoding.UTF8;
mm.SubjectEncoding = System.Text.Encoding.UTF8;
NetworkCredential su = new NetworkCredential(username, password);
sc.Host = smtpServer;
sc.Port = smtpPort;
sc.Credentials = su;
sc.Send(mm);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
For my company, the reason we were having this issue was because the server or machine that was sending the emails was not included on the email server's white list. Once the machines ip address was white listed it started working. You might want to check the email servers black list for the same reason.
Sometimes mails sent that way tends to finish into the spam, expecially if the from address is fantasious. Tryng the raw ftp with telnet as P.Brian.Macket tell you is a good idea.
your default client us network, but when you define the network client you are using some default code (username, password an host).
case "network":
server.DeliveryMethod = SmtpDeliveryMethod.Network;
NetworkCredential credentials = new NetworkCredential("SmtpUserName", "SmtpPassword");
server.Host = "SmtpHost";
server.Port = 26;
server.Credentials = credentials;
break;
I really think that are using an example code and forget to specify your custom configuration.
I apologize for my english.
Is "To" a reserved word in c#? Try changing this and see what you get then.
精彩评论