How to check failure response in email send method using Asp.Net.
The Problem is i didn't get the failure exception.
Please suggest better way.
Here is my code, i'm trying to access the email failure exception...
public static bool sendMail(string strTo, string strSubject, string strName, string strbody)
{
try
{
strName = strName == "" ? "Sir/Madam" : ("Dear " + strName + ",");
StringBuilder mailbody = new StringBuilder();
SmtpClient mailClient = null;
MailMessage message = null;
mailClient = new SmtpClient();
message = new MailMessage();
mailClient.Host = ConfigurationManager.AppSettings["SMTP_MAIL_SERVER"];
mailClient.Port = int.Parse(ConfigurationManager.AppSettings["PORT"]);
//network credentials
string strMailUserName = ConfigurationManager.AppSettings["FROM_ADDR"];
string strMailPassword = ConfigurationManager.AppSettings["FROM_ADDR_PASS"];
string strWebSiteURL = ConfigurationManager.AppSettings["LinkTosite"];
mailClient.EnableSsl = true;
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strMailUserName, strMailPassword);
mailClient.UseDefaultCredentials = true;
mailClient.Credentials = SMTPUserInfo;
string strFromMail = ConfigurationManager.AppSettings["FROM_ADDR"];
MailAddress fromAddress = new MailAddress(strFromMail, "TEST (Administrator)");
message.From = fromAddress;
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess;
//to mail address
message.To.Add(strTo);
message.Subject = "ChatOnGo : " + strSubject;
//mailbody.AppendFormat("<link href='" + strWebSiteURL + "admin/css/bestlogin.css' rel='stylesheet' type='text/css' />");
mailbody.AppendFormat("<div class='dlogin_bg'><div class='dlogin_bg_top'></div><div class='dlogin_bg_bottom'><h2>" + strName + "</h2>");
mailbody.AppendFormat(strbody);
mailbody.AppendFormat("<br/><br/><span>Regards,<br /><a href='" + strWebSiteURL + "'>ChatOnGo Admin</a></span></div></div>");
message.Body = mailbody.ToString();
message.IsBodyHtml = true;
mailClient.SendMailAsync(message);
message = null;
mailClient = null;
return true;
}
catch (SmtpFailedRecipientsException ep)
{
Console.WriteLine(ep.Message);
return false;
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
return false;
}
}
I assume you are using gmail to send email.
You should send the email at least once and if the email is not valid you will receive failure notification.
You can create a nightly/hourly job to check these failure emails and mark them as invalid in your database.
Below is the link to read emails programatically :
http://www.aspsnippets.com/Articles/Fetch-and-read-email-messages-with-attachments-from-GMAIL-POP3-mail-server-in-ASPNet.aspx
I hope this helps!
I am not sure but can you try to send mail without Async (SendMailAsync), just try to call normal send method, probably you will get exception details.
Related
I've published my app and it is now running from IIS. the problem is that the email function in my controller no longer works when running on IIS (the email function does not send email)
I have an email function on my mvc application and when I run it, it does send an email. The problem starts after I've published my app, Its running on IIS now but the email function does not send the email anymore. How do I go about fixing this?
[HttpPost]
public JsonResult SendMailToUser(string lt, string reason, string name, string fr, string ed)
{
bool result = false;
result = SendMail("ntulisakhile8#gmail.com", "Leave Reaquest", "Hi Sensei,<br />I would like to take a " + lt + " leave<br/><strong>From:</strong> " + fr + " <strong>To:</strong> " + ed + " <br/>Reason: " + reason + "<br/>Regards<br/>" + name + "<br/><a href=~/Response.html>Respond</a>");
return Json(result, JsonRequestBehavior.AllowGet);
}
public bool SendMail(string toEmail, string subject, string emailBody)
{
try
{
string senderEmail = System.Configuration.ConfigurationManager.AppSettings["SenderEmail"].ToString();
string senderPassword = System.Configuration.ConfigurationManager.AppSettings["SenderPassword"].ToString();
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(senderEmail, senderPassword);
MailMessage mailMessage = new MailMessage(senderEmail, toEmail, subject, emailBody);
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = UTF8Encoding.UTF8;
client.Send(mailMessage);
return true;
}
catch (Exception ex)
{
return false;
}
}
This is my code:
string from = "rashmi#example.com";
string to = "rashmi#example.com";
string mailSubject = "mail demo";
string mailBody = "mail sent successfully";
MailMessage mess = new MailMessage(from, to, mailSubject, mailBody);
mess.IsBodyHtml = true;
SmtpClient emailClient = new SmtpClient("192.168.43.1", 25); //Server ip & port
emailClient.UseDefaultCredentials = false;
emailClient.Credentials = new System.Net.NetworkCredential("rashmi#example.com", "****password****");
try
{
emailClient.Send(mess);
Response.Write("message sent");
}
catch (Exception ex)
{
Response.Write("Exception caught in CreateTestMessage1(): {0}"+ ex.ToString());
}
but I get this error:
Exception caught in CreateTestMessage1(): {0}System.Net.Mail.SmtpException: Service not available, closing transmission channel. The server response was: Cannot connect to SMTP server 192.168.43.1 (192.168.43.1:25), connect error 10061
at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message) at mail_demo_project.register_mail_demo.submit_Click(Object sender, EventArgs e) in e:\dot net\projects\mail demo project\mail demo project\register_mail_demo.aspx.cs:line 53
error occured...
Use this code to send email:
string From = "fromemailaddress#gmail.com";
MailAddress mailAddress = new MailAddress(From, "Contact Us");
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("toemailaddress#gmail.com");
mailMessage.From = mailAddress;
mailMessage.Subject = Txt_Subject.Text;
string mailBody = "User Email: " + Txt_msg.Text + "<br/> User Name: " + Txt_Name.Text + "<br/> Message: " + Txt_msg.Text ;
mailMessage.Body = mailBody;
mailMessage.Priority = MailPriority.Normal;
mailMessage.IsBodyHtml = true;
System.Net.NetworkCredential credential = new System.Net.NetworkCredential(From, "password");
SmtpClient smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = false;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = credential;
smtpClient.Send(mailMessage);
and you have to make some security modification in your gmail account in security section :Allow less secure apps: YES
I had created an application to send bulk mail but my application is taking too much time to send all the emails. This was my code:
foreach (GridViewRow grow in GridView1.Rows)
{
string Emails = grow.Cells[0].Text.Trim();
string file = Server.MapPath("~/Mail.html");
string mailbody = System.IO.File.ReadAllText(file);
string to = Emails;
string from = "xyz#gmail.com";
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Auto Response Email";
msg.Body = mailbody;
msg.BodyEncoding = Encoding.UTF8;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.live.com", 25);
client.UseDefaultCredentials = false;
System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential("xyz#gmail.com", "password");
client.EnableSsl = true;
client.UseDefaultCredentials = true;
client.Credentials = basicCredential;
try
{
client.Send(msg);
cnfrm.Text = "Email Sended Successfully";
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
So for it's solution I tied to use the Parallel.ForEach but I am finding myself unable to use it with GridView.
Parallel.ForEach(GridView1.Rows, GridViewRow =>
{
string Emails = grow.Cells[0].Text.Trim();
string file = Server.MapPath("~/Mail.html");
string mailbody = System.IO.File.ReadAllText(file);
string to = Emails;
string from = "xyz#gmail.com";
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Auto Response Email";
msg.Body = mailbody;
msg.BodyEncoding = Encoding.UTF8;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.live.com", 25);
client.UseDefaultCredentials = false;
System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential("xyz689#gmail.com", "password");
client.EnableSsl = true;
client.UseDefaultCredentials = true;
client.Credentials = basicCredential;
try
{
client.Send(msg);
cnfrm.Text = "Email Sended Successfully";
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
});
Could anyone tell me how I can use it!!
I don't think you can access the Gridview rows like that with multiple threads, extract the text in your main thread then use foreach. Also take a look at Partitioner to use with ForEach
Here's an example of how it might look:
var emailtext = new List<string>()
foreach (GridViewRow grow in GridView1.Rows)
{
emailtext.Add(grow.Cells[0].Text.Trim());
}
//split and load balance the List
Partitioner<string> partitioner = Partitioner.Create(emailtext, true);
Parallel.ForEach(partitioner, mailtext =>
{
//your email sending code here
//NB: 'mailtext' is your string to send
}
Note: Most mail providers limit the number of emails you send per session or per hour, so you may need to consider this in your application.
Here I am in a strange situation. When I send the email from localhost it is working fine but when I upload the page to the server and try to send email, I get the following error
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required
I'm displaying the error message in a label for testing purpose and the try is also misplaced I know, I will set it later.
the code I am using is
if (Page.IsValid)
{
try
{
StringBuilder message = new StringBuilder();
message.Append("Hello My Name is ");
message.Append(txtName.Text);
message.AppendLine();
message.AppendLine("My Contact Number " + txtContactNumber.Text.ToString());
message.AppendLine();
message.AppendLine();
message.AppendLine("My Email Id Is " + txtFromEmailAddress.Text.ToString());
message.AppendLine();
message.Append(txtEmailBody.Text);
MailMessage mailMessage = new MailMessage("xxx#gmail.com", "yyy#gmail.com");
mailMessage.Subject = "New Client Query";
mailMessage.Body = message.ToString();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 25);
//smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = "xxx#gmail.com",
Password = "password"
};
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
txtContactNumber.Text = "";
txtFromEmailAddress.Text = "";
txtName.Text = "";
txtEmailBody.Text = "";
lblEmailStatus.Text = "Email Sent Successfully.";
lblEmailStatus.ForeColor = System.Drawing.Color.Yellow;
}
catch(Exception ex)
{
lblEmailStatus.Text = ex.Message + " <br> " + ex.Source;
}
}
else
{
lblEmailStatus.Text = "Error! Email Not Sent ";
lblEmailStatus.ForeColor = System.Drawing.Color.Yellow;
}
I have googled for a couple of hours and checked links at this site as well but I still cant figure it out.
Now I request you guys here if any one have any solutions / hint.
Try this
public string SendEmailTest(String EmailMessage, String FromMail, String MailPassword, String MailServer, String To, String CC, String BCC, String DisplayName, String Subject, String Attachment)
{
try
{
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress;
fromAddress = new MailAddress(FromMail);
smtpClient.Host = MailServer;
smtpClient.Port = 25;
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(FromMail, MailPassword);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = SMTPUserInfo;
message.From = fromAddress;
message.To.Add(new MailAddress(To, DisplayName));
if (CC != "")
message.CC.Add(new MailAddress(CC, DisplayName));
if (BCC != "")
message.Bcc.Add(new MailAddress(BCC, DisplayName));
message.Subject = Subject;
message.IsBodyHtml = true;
message.Body = EmailMessage;
if (Attachment != "")
message.Attachments.Add(new Attachment(Attachment));
message.Priority = MailPriority.High;
smtpClient.Send(message);
return "SendEmail";
}
catch (Exception ex)
{
return "Email :" + ex;
}
}
i got the reason finally .
the email i was sending emails from was kind of hacked some days before and for the security reasons google team had kind of marked my email as unsecure . i changed the emails address and it is working fine thanks you all.
Based on the Google Gmail Documentation it would appear that the Port should be 587 not 25. I found a few other questions that seem to be related here and here.
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
client.UseDefaultCredentials = false;
I have some text boxes like name,email address,phone no. and comment on my page.
I have to send the values to my email address..
How should I do this??
I am doing:
protected void btnSubmit_Click(object sender, EventArgs e)
{
SmtpClient client = new SmtpClient();
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress(txtEmail.Text, txtName.Text);
SmtpClient.Host = "localhost";
SmtpClient.Port = 25;
message.From = fromAddress;
message.To.Add("xyz#gmail.com");
message.Subject = "Feedback";
message.IsBodyHtml = false;
message.Body = txtComment.Text;
SmtpClient.Send(message);
Response.Write("Email successfully sent.");
}
catch (Exception ex)
{
Response.Write("Send Email Failed." + ex.Message);
}
}
and I am getting the following error:
An object reference is required for the nonstatic field, method, or property 'System.Net.Mail.SmtpClient.Send(System.Net.Mail.MailMessage)'
SmtpClient.Host = "localhost";
SmtpClient.Port = 25;
~~~~~~~~~~~~~~~~~~~~
SmtpClient.Send(message);
These lines are attempting to use members of the class SmtpClient. However, as these members are not defined as static, you need to refer to your instance of that class, which you have called client.
Try
client.Host = "localhost";
client.Port = 25;
~~~~~~~~~~~~~~~~~~~~
client.Send(message);
Also, have a read of this article on the differences between class and instance members.
Finally, as SmtpClient implements IDisposable, I would change your code to wrap it in a using block, as this will ensure you are correctly cleaning up your SMTP session after you are finished with it.
using (SmtpClient client = new SmtpClient())
{
// YOUR CODE
}
public static string sendMail(string to, string title, string subject, string body)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
MailAddress fromAddress = new MailAddress(txtEmail.Text, txtName.Text);
if (to == "")
to = fromAddress.Address;
MailAddressCollection m = new MailAddressCollection();
m.Add(to);
mail.Subject = subject;
mail.From = fromAddress;
mail.Body = body;
mail.IsBodyHtml = true;
mail.ReplyTo = fromAddress;
mail.To.Add(m[0]);
smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential(fromAddress.Address, "XXXX");//"XXXX" is the password of the sender.
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtp.Send(mail);
return "done";
}
catch (Exception ex)
{
return ex.Message;
}
}
i had done this:-
protected void btnSubmit_Click(object sender, EventArgs e)
{
MailMessage mailmsg = new MailMessage();
string name = txtName.Text.ToString();
string contact = txtPhoneNo.Text.ToString();
string comment = txtComment.Text.ToString();
string checkIn = txtCheckIn.Text.ToString();
string from = txtEmail.Text.ToString();
mailmsg.To.Add("recipientemailid#gmail.com");
mailmsg.From = new MailAddress(from.Trim());
mailmsg.Subject = "Test message";
mailmsg.Body = "This Query is submitted by user " + name.Trim() + ", "+ contact.Trim() + ", " + comment.Trim() + ", " + checkIn.Trim();
mailmsg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
NetworkCredential credentials = new NetworkCredential("recipientemailid#Gmail.com", "password");
client.Credentials = credentials;
try
{
//try to send the mail message
client.Send(mailmsg);
Response.Write("sent!");
}
catch
{
//some feedback if it does not work
Response.Write("failed!");
}
}
Try
client.Host = "localhost";
client.Port = 465;
~~~~~~~~~~~~~~~~~~~~
client.Send(message);
Do not try to use or manage disposable emails with this because you will be clearly exposed to spam-trappers. Your code is open and very easy to identify who is using the code and from where.