Hooking into SMTP client events - c#

Intro: I am supporting a piece of code that sends a welcome/confirm mail upon successful registration to a site.
The SMTP client times out before sending can complete. According to our Ops department, I am using the correct credentials and SMTP server IP address.
What I want to do is hook into any handshaking, connection, sending, etc events so that I can figure out exactly why the process times out. I've set Server.ScriptTimeOut to 500 seconds on that page, so it can't just be a busy server problem.
My question is this: what events can I handle during this process. The only one I see exposed in SMTPClient is SendCompleted. But I imagine there must be a way to get access to something more low-level?
For reference, here's the code:
//Create and send email
MailMessage mm = new MailMessage();
try
{
mm.From = new MailAddress("admin#site.com");
mm.To.Add(new MailAddress(Recipient));
mm.Subject = Subject;
mm.Body = MailBody;
mm.IsBodyHtml = true;
var c = new NetworkCredential("admin#site.com", "YeOlePassword");
SmtpClient smtp = new SmtpClient("127.0.0.1");//not really, just hiding our SMTP IP from StackOverflow
smtp.UseDefaultCredentials = false;
smtp.Credentials = c;
smtp.Send(mm);
}
catch (Exception x)
{
DateTime CurrentDateTime = DateTime.Now;
String appDateTime = CurrentDateTime.ToString();
String transactionLogEntry = "To: " + Recipient + " " + appDateTime + " " + x.Message;
StreamWriter streamwriter = new StreamWriter(File.Open(MapPath("~/TransactionLog.txt"), FileMode.Append, FileAccess.Write, FileShare.Write));
//Append to file
streamwriter.WriteLine(transactionLogEntry);
//Close file
streamwriter.Close();
}
The error that's logged is simply that a timeout occured while sending a mail to the supplied email address.

I use this to get the buried SMTP messages out.
String transactionLogEntry = "To: " + Recipient + " " + appDateTime + " " + GetFullErrorMessage(x);
.
.
.
private string GetFullErrorMessage(Exception e)
{
string strErrorMessage = "";
Exception excpCurrentException = e;
while (excpCurrentException != null)
{
strErrorMessage += "\"" + excpCurrentException.Message + "\"";
excpCurrentException = excpCurrentException.InnerException;
if (excpCurrentException != null)
{
strErrorMessage += "->";
}
}
strErrorMessage = strErrorMessage.Replace("\n", "");
return strErrorMessage;
}
In my experience, from what you are describing it is related to your SMTP port being blocked by and ISP or your server/web host. Good luck!

Related

Sending email with attachments using loop to different email address using C#

Hellow, I`ve tried to create a pdf files and send them at the same time in a loop to different email address, but it seems the first created file doesnt close to allow the next one to be created, i use the same name (overwriting the file).
here is the code for attaching the email
private void sendEmail(string email)
{
sendInfo = new Label();
sendInfo.Font = new Font("Calibri", 11);
sendInfo.AutoSize = true;
MailMessage mail = new MailMessage("ikwabe04#gmail.com", email, "TESTING THE SALARY SLIP EMAIL SENDER", "Habari Rafiki? Usishitushwe na ujumbe huu, tunajaribu system. Asante.");
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential("ikwabe04#gmail.com", "mikunjoyamwili");
client.EnableSsl = true;
Attachment file = new Attachment("C:/Users/" + Home.computerName + "/AppData/Roaming/SEC Payroll/Receipts/receipt.pdf");
file.Name = "Salary Slip for " + DateTime.Now.ToString("MMMM yyyy") + ".pdf";
mail.Attachments.Add(file);
try
{
client.Send(mail);
Login.RecordUserActivity("Sent the Salary Slip to " + email);
sendInfo.ForeColor = Color.LightGreen;
sendInfo.Text = "Email sent to: " + email + " (" + DateTime.Now.ToLongTimeString() + ")";
information.Controls.Add(sendInfo);
}
catch
{
sendInfo.ForeColor = Color.Orange;
sendInfo.Text = "Email NOT sent to: " + email + " ("+DateTime.Now.ToLongTimeString()+")";
information.Controls.Add(sendInfo);
}
}
here code to create a pdf
using (FileStream file = new FileStream("C:/Users/" + Home.computerName + "/AppData/Roaming/SEC Payroll/Receipts/receipt.pdf", FileMode.Create))
{
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
PdfWriter.GetInstance(pdfDoc, file);
pdfDoc.Open();
pdfDoc.Add(table);
pdfDoc.Add(slp);
pdfDoc.Add(Separator);
pdfDoc.Add(table1);
pdfDoc.Add(Separator);
pdfDoc.Add(Tsh);
pdfDoc.Add(incomeTitle);
pdfDoc.Add(incomeTable);
pdfDoc.Add(totaInc);
pdfDoc.Add(taxDeductionTitle);
pdfDoc.Add(taxDeduction);
pdfDoc.Add(otherDeductionTitle);
pdfDoc.Add(OtherDeduction);
pdfDoc.Add(totaDeduc);
pdfDoc.Close();
file.Close();
}
here is the code for sending email
for (int i = 0; i< table.Rows.Count;i++)
{
PreapareSalarySlip(table.Rows[i][2].ToString(),
table.Rows[i][3].ToString(),
table.Rows[i][5].ToString(),
table.Rows[i][37].ToString()
);
sendEmail(table.Rows[i][38].ToString());
}
here is the Error occured
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\Shadrack Ikwabe\AppData\Roaming\SEC Payroll\Receipts\receipt.pdf' because it is being used by another process.
It isn't the PDF creation process that is locking the file. It's the attachment. The Attachment class locks the file and doesn't release the lock until it is disposed. You're getting the exception because you're trying to attach the same file to two different emails without releasing the lock by disposing of the attachment.
SmtpClient and MailMessage are also disposable. Disposing of the MailMessage is sufficient; when it is disposed, it also disposes its attachments. However, I consider it better to make it explicit.
You should be disposing of them properly using a using:
using (MailMessage mail = new MailMessage("ikwabe04#gmail.com", email, "TESTING THE SALARY SLIP EMAIL SENDER", "Habari Rafiki? Usishitushwe na ujumbe huu, tunajaribu system. Asante."))
using (SmtpClient client = new SmtpClient("smtp.gmail.com"))
using (Attachment file = new Attachment("C:/Users/" + Home.computerName + "/AppData/Roaming/SEC Payroll/Receipts/receipt.pdf"))
{
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential("ikwabe04#gmail.com", "mikunjoyamwili");
client.EnableSsl = true;
file.Name = "Salary Slip for " + DateTime.Now.ToString("MMMM yyyy") + ".pdf";
mail.Attachments.Add(file);
try
{
client.Send(mail);
Login.RecordUserActivity("Sent the Salary Slip to " + email);
sendInfo.ForeColor = Color.LightGreen;
sendInfo.Text = "Email sent to: " + email + " (" + DateTime.Now.ToLongTimeString() + ")";
information.Controls.Add(sendInfo);
}
catch
{
sendInfo.ForeColor = Color.Orange;
sendInfo.Text = "Email NOT sent to: " + email + " ("+DateTime.Now.ToLongTimeString()+")";
information.Controls.Add(sendInfo);
}
}

Send Email from Windows Service: Transaction failed. the server response was 5.7.1 client host rejected access denied

The below code is working fine from Windows Form, but not working from Windows Services.
The service is running on Windows XP.
I have tried changing the log on user, but did not work.
Error: Transaction failed. the server response was 5.7.1 client host
rejected access denied
private void SendEmailToHO()
{
try
{
int mailSentSuccessfully = 0;
MailAddress to = new MailAddress(mailTo);
MailAddress from = new MailAddress(mailFrom);
using (MailMessage mail = new MailMessage(from.Address, to.Address))
{
int attachmentCount = 0;
try
{
foreach (string fileName in fileEntries)
{
Attachment attachment = new Attachment(fileName);
mail.Attachments.Add(attachment);
attachmentCount++;
}
SmtpClient client = new SmtpClient(mailHost, port);
if (enableSSL == "Y")
{
client.EnableSsl = true;
}
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(mailUser, mailPassword);
mail.Subject = "Email Subject " + clientID;
mail.Body = "Attached please find the files: " + clientIDTitle;
if (attachmentCount > 0)
{
//
client.Send(mail);
//if no error, this code will work.
mailSentSuccessfully = 1;
new MyApp.LogWriter("Sent mail to " + to.Address + ", \nAttachment count = " + attachmentCount);
}
else
{
new MyApp.LogWriter("Attachment count = " + attachmentCount);
}
}
catch (Exception ex)
{
new MyApp.LogWriter("Send mail failed. Cause: " + ex.Message
+ "\n Inner Exception: " + ex.InnerException);
}
}
}
catch (System.Exception ex)
{
new BTCClient.LogWriter("Email Error '" +
ex.Message + "'");
}
}
I was facing the same issue, To resolve this issue you need to contact your email server's service provider and tell them to give access to your server IP.

I can send smtp message on a localHost But i cant send it on a Live WebSite

im using Asp.net And I have the Umbraco Cms on my project
i implemented The Send message using razor syntax
im submitting a from to the following razor syntax
#{ if (IsPost)
{
string name = Request["name"];
string email = Request["email"];
string phone = Request["phone"];
string city = Request["city"];
string note = Request["note"];
NetworkCredential basicCredential =new NetworkCredential("*****#gmail.com", "******");
MailMessage mail = new MailMessage();
//var from = new MailAddress(Email.Text);
mail.From = new MailAddress(email);
mail.To.Add("tupacmuhammad5#gmail.com");
mail.Subject = "Torcan WebSite Contact Us";
mail.IsBodyHtml = false;
mail.Body = "You just got a contact email:\n" +
"Name: " + name + "\n"
+ "Email: " + email + "\n"
+ "TelePhone: " + phone + "\n"
+ "Address: " + city + "\n"
+ "Message: " + note + "\n";
SmtpClient smtp = new SmtpClient();
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Host = "smtp.gmail.com";
smtp.Credentials = basicCredential;
smtp.EnableSsl = true;
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
}
finally
{
smtp.Dispose();
}
}
}
it works perfect on My localHost But on a live server its thorws a runtime error "after i remove the try catch "
i cant find out what seems to be problem
im writing this code in umbraco backoffice tamplate i have the server on onther country and i dont have access to it any help ? please ?
The Problem was that the Server is located in Germany so when the server tries to open my Gmail account. its a different country and never seen action from there.
so all i had to do is to open my gmail via remote access on the server machine via a browser and confirmed it was me then every thing worked perfectly.

Getting "The specified string is not in the form required for an e-mail address." errror

string email = "select seller.emailid from seller inner join cars on seller.sid=cars.sid where cars.carid='" + lbllid + "' ";
GridView1.EditIndex = -1;
MailMessage MyMailMessage = new MailMessage("****#gmail.com", email, "Ruby Cabs Email Confirmation", Environment.NewLine + " This is an email automated sevice." + Environment.NewLine + "Your car has been approved. Thank you for taking out time to fill the data." + Environment.NewLine + "Regards," + Environment.NewLine + "Ruby Cabs");
MyMailMessage.IsBodyHtml = false;
NetworkCredential mailAuthentication = new NetworkCredential("****#gmail.com", "****");
SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = mailAuthentication;
I have checked the query on sql server and it works fine. Can any one tell whats the issue
You're putting a SQL query in the email field when calling new MailMessage(...).
You'll need to run the query against your SQL server, get the result set, extract the email address from said result set, and use THAT as your email address.
The debugger is your friend.

how to solve non-local email authentication?

in 3.5 .Net Framework i have a problem to sending an email on server.
Code-
MailMessage message = new MailMessage();
message.From=new MailAddress("CMC Enquiry" + "<my1#domain.in>");
message.To.Add(new MailAddress("vishalpatel8086#gmail.com"));
message.CC.Add(new MailAddress("varun_aone#yahoo.com"));
message.Subject = "Enquiry from CMC site";
string p = "<b>Name: </b>" + TextBox1.Text;
p += "<br><b>Mobile:</b> " + TextBox3.Text;
p += "<br><b>Mail ID:</b> " + TextBox2.Text;
p += "<br><b>Address:</b> " + TextBox4.Text;
p += "<br><b>City:</b> " + TextBox5.Text;
p += "<br><b>Location:</b>" + locationlst.SelectedItem.Text;
p += "<br><b>College:</b> " + TextBox11.Text;
p += "<br><b>Course:</b> " + DropDownList3.SelectedItem.Text;
p += "<br><b>Query:</b> " + TextBox12.Text;
message.Body = p;
message.IsBodyHtml = true;
SmtpClient SMTPServer = new SmtpClient("localhost");
// try
// {
SMTPServer.Send(message);
//result = "Your Enquiry has been Submitted !!";
Label5.Text = "Your Enquiry has been Submitted !!";
//Response.Write("<script language=JavaScript> alert('Your Enquiry has been Submitted !!'); </script>");
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox11.Text = "";
TextBox12.Text = "";
DropDownList3.SelectedIndex = 0;
// }
// catch
// {
// Label5.Text = "Low Server Problem !!Your Enquiry Not Submitted";
//Response.Write("<script language=JavaScript> alert('Server Problem !!Your Enquiry Not Submitted'); </script>");
// }
}
else
{
Label5.Text = "Server Problem !!Your Enquiry Not Submitted";
}
}
This code is working my other web hosting server with my different website but is not working with new web site . A error is being occured like -
Bad sequence of commands. The server response was: This mail server requires authentication when attempting to send to a non-local e-mail address. Please check your mail client settings or contact your administrator to verify that the domain or address is defined for this server.
Error Is -
Line 83: SMTPServer.Send(message);
Source File: c:\inetpub\vhosts\cmcent.in\httpdocs\enquiry.aspx.cs
Line: 83
Your SmtpClient code needs to be revised as follow:
//Set your smtp client settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.yourdomain.com"; //set with your smtp server
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential("fromEmail#yourdomain.com", "fromEmailPassword");
smtp.Timeout = 20000;
}
// Now send your email with this smtp
smtp.Send(message);
Optionally you can also try to enable/disable ssl & changing the port.

Categories