Loop for resending smtp email on failure to send - c#

I have a service that sends an email after a user registers. Every once in a while, a user contacts support with the complaint that they aren't receiving the email, so I've made a list of possible issues, one of which is a smtp failure to send email, which I noticed occasionally when I would step through the code. I want to write a simple loop that tries to resend the email a couple of times on failure to send, but I'm not sure how to go about doing that. I'd appreciate any advice on the subject.
public void MusicDownloadEmail(string email)
{
try
{
var smtp = new SmtpClient();
var mail = new MailMessage();
const string mailBody = "Body text";
mail.To.Add(email);
mail.Subject = "Mail subject";
mail.Body = mailBody;
mail.IsBodyHtml = true;
smtp.Send(mail);
}
catch (Exception ex)
{
var exception = ex.Message.ToString();
//Other code for saving exception message to a log.
}
}

Something like this should do the trick:
public void MusicDownloadEmail(string email)
{
int tryAgain = 10;
bool failed = false;
do
{
try
{
failed = false;
var smtp = new SmtpClient();
var mail = new MailMessage();
const string mailBody = "Body text";
mail.To.Add(email);
mail.Subject = "Mail subject";
mail.Body = mailBody;
mail.IsBodyHtml = true;
smtp.Send(mail);
}
catch (Exception ex) // I would avoid catching all exceptions equally, but ymmv
{
failed = true;
tryAgain--;
var exception = ex.Message.ToString();
//Other code for saving exception message to a log.
}
}while(failed && tryAgain !=0)
}

You could do it recusively
Firstly define the maximum amount of retries
public const int MAX_RETRY_COUNT = 3;
Then call the method using the retry count
MusicDownloadEmail("code#mail.com", MAX_RETRY_COUNT);
And modify the method as follows
public static void MusicDownloadEmail(string email, int retryCountsLeft) {
if (retryCountsLeft > 1) {
try {
var smtp = new SmtpClient();
var mail = new MailMessage();
const string mailBody = "Body text";
mail.To.Add(email);
mail.Subject = "Mail subject";
mail.Body = mailBody;
mail.IsBodyHtml = true;
smtp.Send(mail);
} catch (Exception ex) {
var exception = ex.Message.ToString();
//Other code for saving exception message to a log.
MusicDownloadEmail(email, --retryCountsLeft);
}
}
}

Related

Reading file line by line in listbox

I tried to make my own email sender, but now I have issued to execute the mail list line by line. My current code is
foreach (string emails in listBoxEmails.Items)
{
mail.From.Add(new MailboxAddress(textBoxSendName.Text, textBoxSendFrom.Text));
mail.To.Add(new MailboxAddress(emails));
client.Send(mail);
Thread.Sleep(1000);
}
I want the the program run like, after I sent the 1st mail of the list was successful, it will send the second mail. but from my code that I got from google, it will directly sent all the email together.
You should write a method something like that returns true or false.
foreach (string email in listBoxEmails.Items)
{
if (!sendMail(textBoxSendName.Text, textBoxSendFrom.Text, email)){
break;
}
}
private bool sendMail(string name, string from, string to)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.????.???");
mail.From = new MailAddress(from, name, Encoding.UTF8);
mail.To.Add(to);
mail.Subject = "Test Mail";
mail.Body = "This is for testing...";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}

How to create an SMTP mail?

I tried to send mail from my asp.net web application.
I want to send my application password to the user mail id, for that I took the password from datatabase using getdetailss function.
btn4getPwd is the button calling the mailing function.
txtusername.Text is the text box containing sending mail address. All values are receiving correctly, no error occur but it's not working ..!
protected void btn4getPwd_Click(object sender, EventArgs e)
{
if (txtusername.Text.Trim() != "")
{
em.username = txtusername.Text.Trim();
DataTable forget = em.getdetailss(10);
string passwd = (forget.Rows[0]["PassCode"].ToString());
try
{
string Subject = "Your NLS Password";
string Body = passwd;
string ToEmail = txtusername.Text.Trim();
string SMTPUser = "mymail#gmail.com", SMTPPassword = "pswd";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(SMTPUser, "AspnetO");
mail.To.Add(ToEmail);
mail.Body = Body;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.Normal;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.Credentials = new System.Net.NetworkCredential(SMTPUser, SMTPPassword);
smtp.EnableSsl = true;
smtp.Send(mail);
Response.Write("<script language=javascript>alert('Mail send...!! ')</script>");
}
catch (SmtpException ex)
{
lbl4get.Text = "SmtpException ";
}
catch (Exception ex)
{
lbl4get.Text = "Exception";
}
}
else { Response.Write("<script language=javascript>alert('Invalid USERNAME...!! ')</script>"); }
}
smtp.Port = 25; is default port but for as you are sending over SSL use port 587 or 465 (nonstandard, but sometimes used for legacy reasons). Assume NetworkCredential are correct.

Exception sending email using Asp.net

I've been tring to make a webpage use Gmail as a smtp Server to send emails with Asp.net. Here is the link for the settings that google has set for such occasion.
https://support.google.com/a/answer/176600?hl=en
Every time I try to send an email I get the "Exception caught in RetryIfBusy()" message..
Any ideas?...Here is my code below:
[System.Web.Services.WebMethod]
public static void SendMessage(string toEmail)
{
MailMessage msg = new MailMessage("myEmail#gmail.com", toEmail);
msg.Subject = "Email Subject";
msg.Body = "Here goes email body";
msg.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
System.Net.NetworkCredential netCred = new System.Net.NetworkCredential();
netCred.UserName = "myEmail#gmail.com";
netCred.Password = "myPassword";
smtp.Credentials = netCred;
smtp.Port = 465;
smtp.EnableSsl = true;
try
{
smtp.Send(msg);
Console.WriteLine("Email Successfully sent!!");
}
catch (SmtpFailedRecipientsException ex)
{
for (int i = 0; i < ex.InnerExceptions.Length; i++)
{
SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
if (status == SmtpStatusCode.MailboxBusy ||
status == SmtpStatusCode.MailboxUnavailable)
{
Console.WriteLine("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
smtp.Send(msg);
}
else
{
Console.WriteLine("Failed to deliver message to " +
ex.InnerExceptions[i].FailedRecipient);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in RetryIfBusy(): " +
ex.ToString());
}
}
You are using a wrong port on Google's SMTP server. Should be:
smtp.Port = 587;

Sending email in C#

I am working on a page where I have to send an email in C#.
I followed the codes on
http://blogs.msdn.com/b/mariya/archive/2006/06/15/633007.aspx
and came upon this two exceptions
A first chance exception of type 'System.Net.Mail.SmtpException' occurred in System.dll. A first chance exception of type
'System.Threading.ThreadAbortException' occurred in mscorlib.dll
Here are the codes I implemented. I can't seem to figure what went wrong.
//Send email notification - removed actual email for this question
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
MailAddress from = new MailAddress("myemail#gmail.com", "My name is here");
MailAddress to = new MailAddress("anotherpersonsemail#gmail.com", "Subject here");
MailMessage message = new MailMessage(from, to);
message.Body = "Thank you";
message.Subject = "Successful submission";
NetworkCredential myCreds = new NetworkCredential("myemail#gmail.com",
"mypassword", "");
client.Credentials = myCreds;
try
{
client.Send(message);
Console.Write(ex.Message.ToString());
}
catch (Exception ex)
{
Console.Write(ex.Message.ToString());
}
For sharing purposes, I managed to resolve my problem by enabling access for less secure apps in Gmail.
It works like a charm now! https://www.google.com/settings/security/lesssecureapps
To authenticate SMTP in Outlook, the articles below are very useful too.
http://www.tradebooster.com/web-hosting-articles/how-to-enable-smtp-authentication-in-outlook-2010/
https://www.authsmtp.com/outlook-2010/default-port.html
//bulk Emails using mailkit you have to import it by nuget manager
//set in gmail https://myaccount.google.com/lesssecureapps?pli=1 to be on
// Read Text File
public void ReadFileAndSend()
{
using (StreamReader reader = new StreamReader(#"d:\Email.txt"))
{
while (!(reader.ReadLine() == null))
{
String line = reader.ReadLine();
if (line != "")
{
try
{
Send("", line.Trim());
Thread.Sleep(500);
}
catch
{
}
}
}
Console.ReadLine();
}
}
public void Send(String FromAddress,String ToAddress)
{
try
{
string FromAdressTitle = "";
string ToAdressTitle = "";
string Subject = "";
string BodyContent = "";
string SmtpServer = "smtp.gmail.com";
int SmtpPortNumber = 587;
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
mimeMessage.Subject = Subject;
mimeMessage.Body = new TextPart("html")
{
Text = BodyContent
};
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.Connect(SmtpServer, SmtpPortNumber, false);
client.Authenticate("your email", "pass");
client.Send(mimeMessage);
Console.WriteLine("The mail has been sent successfully !!");
client.Disconnect(true);
}
}
catch (Exception ex)
{
throw ex;
}
}
Answer Update 2023
After Google introduced a Two-step verification system in Google Accounts, it's not easy to use Gmail for your own personal usage so to solve this problem, I figured out a way to use Gmail as an email medium to send emails using C#.
The C# code for email service is included here: https://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html
Following just the 2-step tutorial from the above link, you can fix your issue in no time.

Smtp mail delivered unsuccessfully

I am using Smtp to send mail.A message was sent successfully but it was not delivered. What is the reason behind this.Is this a problem in mailing server?The message sending process is working fine for the last couple of years.The issue came first time.
public bool SendMail(string p_strFrom, string p_strDisplayName, string p_strTo, string p_strSubject, string p_strMessage , string strFileName)
{
try
{
p_strDisplayName = _DisplayName;
string smtpserver = _SmtpServer;
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(_From,_DisplayName);
smtpClient.Host = _SmtpServer;
smtpClient.Port = Convert.ToInt32(_Port);
string strAuth_UserName = _UserName;
string strAuth_Password = _Password;
if (strAuth_UserName != null)
{
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strAuth_UserName, strAuth_Password);
smtpClient.UseDefaultCredentials = false;
if (_SSL)
{
smtpClient.EnableSsl = true;
}
smtpClient.Credentials = SMTPUserInfo;
}
message.From = fromAddress;
message.Subject = p_strSubject;
message.IsBodyHtml = true;
message.Body = p_strMessage;
message.To.Add(p_strTo);
try
{
smtpClient.Send(message);
Log.WriteSpecialLog("smtpClient mail sending first try success", "");
}
catch (Exception ee)
{
Log.WriteSpecialLog("smtpClient mail sending first try Failed : " + ee.ToString(), "");
return false;
}
return true;
}
catch (Exception ex)
{
Log.WriteLog("smtpClient mail sending overall failed : " + ex.ToString());
return false;
}
}
A message was sent successfully but it was not delivered
If it was sent successfully from your mailing server then the possible reason of non delivery can be that the mail filter on client blocked it or is delivered in the junk.

Categories

Resources