SmtpClient exception not stepping into SmtpFailedRecipientsException - c#

I am trying to show an error message for failed recipients in my asp.net webpage. For some reason the code is not stepping into the SmtpFailedRecipientException:
SmtpClient client = new SmtpClient("smtp.server.com", 25) { Credentials = new NetworkCredential("any#one.com", "123456") };
using (var message = new MailMessage { })
{
message.From = new MailAddress(salesPersonDropDownList.SelectedItem.Text);
message.To.Add(mailToTextBox.Text);
message.CC.Add(mailToCCTextBox.Text);
message.CC.Add(mailToCCTextBox2.Text);
message.CC.Add(mailToCCTextBox3.Text);
message.Subject = mailSubjectTextBox.Text;
message.Body = mailBodyTextBox.Text;
try
{
client.Send(message);
}
catch (SmtpFailedRecipientsException ex)
{
string strSmtpFailedRecipientsException = "test";
}
catch (Exception ex)
{
string strException = "test";
}
}
The code is stepping properly into the the second "catch" but for some reason no into the SmtpFailedRecipientsException. Anyone can tell what I am doing wrong?
Thanks in advance

I found the problem by myself.
The SmtpFailedRecipientsException is for exceptions with two or more failed recipients - and in my case I always had only one failed recipient.
For one failed recipient I had to use the SmtpFailedRecipientException.

Related

HTML tags and attributes defect client from receiving email using SmtpClient via anonymous account

I am cracking my head to find a solution for that strange behavior.
I have made a lot of tests and experiments and tried to play around with my code but with no success.
Server: Windows service on windows server 2012 .net framework 4.0.
Client: windows 7 os, outlook 2010.
Problem: html tags and \ or attributes inside the message body are affecting client from receiving emails and no exception is thrown on the server.
there are several cases that html inside the body message is preventing from the client to receive email to his outlook inbox.
Example: if i am calling SendHtmlEmail() like that everything works fine as expected:
Exchange.InvokeEmail.SendHtmlEmail("testTrue", "<div dir=rtl><br/>test</div>", "jonathana#xxx.net",null, "מערכת ניהול פרויקטים", null,true);
but if i am removing the <br/> tag, the client is not receiving email and no exception is thrown:
Exchange.InvokeEmail.SendHtmlEmail("testTrue", "<div dir=rtl> test</div>", "jonathana#xxx.net",null, "מערכת ניהול פרויקטים", null,true);
another example is using the dir attribute:
"<body dir=rtl> test </body>" // not working
"<body ><br/>test</body>" // working
"<div dir=rtl> test </div>" // not working
"<div ><br/>test</div>" // working
I have tried to change Encoding of the body but nothing helps. also, because no exception is raised I assume the problem is on client side(?) (outlook 2010, windows 7 os).
Thank you.
Server code:
public static bool SendHtmlEmail(string _subject, string _body,
string _to, string _cc = null,
string _DisplayName = "מערכת ניהול פרויקטים", string _FileName = null,bool Isanonymous = true)
{
try
{
MailMessage msg = new MailMessage();
// from
if (Isanonymous == false)
msg.From = new MailAddress("pmsapp#partner.co.il");
else
msg.From = new MailAddress("PmsApplication#partner.co.il", _DisplayName);
// to
foreach (var address in _to.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
msg.To.Add(address);
}
// cc
if (_cc != null && _cc.Contains("#"))
{
foreach (var address in _cc.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
msg.CC.Add(address);
}
}
msg.Subject = _subject;
msg.Body = _body;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
if (Isanonymous==false)
client.Credentials = new System.Net.NetworkCredential("xxxxx", "xxxxxxx");
client.Port = 25;
client.Host = ConfigurationManager.AppSettings["Exchange.SmtpServerName"];
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Send(msg);
return true;
}
catch (Exception ex)
{
string error = ex.ToString(); // TODO: write to database
return false;
}
}

Mail Code Issue(It works time to time)

Hello I'm building a new site. But my usual mail code working only sometimes with this site.I was able to send mail within 01.00 - 01.10 and get a error "Failure to send mail" for 15 minutes.And now I'm able to send again. Its probably a issue with my hosting firm but can you review the code just to be safe? Thanks in advance.
[HttpPost]
public string processData(PersonDTO p)
{
try
{
var bdy = string.Format("Alınacak Yer: {0}\nAd Soyad: {1}\nTarih: {2}\nSaat: {3}\nBırakılacak Yer:{4}\nEmail: {5}\nUçuş No: {6}\nTelefon: {7}\nAdres Tarifi: {8}\nYolcu Sayısı: {9}", p.PickupSite, p.Name, p.Date, p.Time, p.DropSite, p.Email, p.FlightNumber, p.Phone, p.AddressLocation, p.NumberOfPassengers);
var msg = new MailMessage();
msg.From = new MailAddress("system#globalairporttransfer.com");
msg.To.Add("info#globalairporttransfer.com");
msg.Subject = "Yeni Istek";
msg.Body = bdy;
msg.IsBodyHtml = false;
var client = new SmtpClient("mail.globalairporttransfer.com", 25);
client.Credentials = new NetworkCredential("system#globalairporttransfer.com", "mypasswordishere");
client.EnableSsl = false;
client.Send(msg);
return "Kaydınız alındı. En kısa sürede ileşime geçeceğiz.";
}
catch (SmtpException e){return "Mesaj Gönderilemedi ! Hata Mesajı: \n" +e.Message;}
catch (SocketException e) { return "Mesaj Gönderilemedi ! Hata Mesajı: \n" + e.Message; }
catch (FormatException e) { return "Mesaj Gönderilemedi ! Hata Mesajı: \n" + e.Message; }
}
}
After fighting several hours with my hosting firm I proved that there is a problem with their end. After some configuration from their end I noticed Dns couldnt be resolved. If you have that problem you can try write ip adress of smtp instead of name.. I hope it helps some
var client = new SmtpClient("Ip of the smtp server", 25);

Fire and forget with async

Consider this code:
public async Task<Status> SendMessage(Message message)
{
List<IMessage> _messageDispatchers = new List<IMessage>();
try
{
Object[] args = new Object[] { _message };
IMessage endpoint = (IMessage)Activator.CreateInstance(Type.GetType(_message.AgentDLLName), args);
_messageDispatchers.Add(endpoint);
foreach (IMessage dispatcher in _messageDispatchers)
{
await Task.Run(() => dispatcher.SendMessage(_message));
}
return await Task.Run(() => Status.Success);
}
catch (Exception ex)
{
logger.Log(LoggerLevel.Error, ex.Message);
return Status.EmailSendingFailed;
}
}
the SendMessage:
public async Task<Status> SendMessage(OutboundMessage outboundmessage)
{
string strMessage = string.Empty;
string subject = string.Empty;
MessageServices objService = new MessageServices();
try
{
var config = (from SmtpConfigurationElement ms in AppConfiguration.Instance.Smtps
where ms.Key == "smtp"
select ms).Single();
SmtpClient smtpClient = new SmtpClient(config.Host);
smtpClient.Port = Convert.ToInt32(config.port);
smtpClient.EnableSsl = true;
smtpClient.Credentials = new NetworkCredential(config.UserName, config.Password);
string[] strToList = outboundmessage.ToList.Split(';');
MailMessage mail = new MailMessage();
mail.From = new MailAddress(outboundmessage.FromAddress);
if (strToList.Length > 0)
{
for (int j = 0; j < strToList.Length; j++)
{
mail.To.Add(strToList[j]);
}
}
else
{
_LOGGER.Log(LoggerLevel.Information, "SMTP Mail Send failed as ToList is not correct");
return Status.Failed;
}
if (!string.IsNullOrEmpty(outboundmessage.CCList))
{
string[] strCCList = outboundmessage.CCList.Split(';');
if (strCCList.Length > 0)
{
for (int k = 0; k < strCCList.Length; k++)
{
mail.CC.Add(strToList[k]);
}
}
}
if (!string.IsNullOrEmpty(outboundmessage.Attachments))
{
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(outboundmessage.Attachments);
mail.Attachments.Add(attachment);
}
strMessage = await objService.ReplaceMessageWithPlaceholders(outboundmessage.PlaceholderValues, outboundmessage.MessageBody);
subject = await objService.ReplaceMessageWithPlaceholders(outboundmessage.PlaceholderValues, outboundmessage.Subject);
mail.Body = strMessage;
mail.Subject = subject;
mail.IsBodyHtml = true;
await Task.Run(() => smtpClient.Send(mail));
return Status.Success;
}
catch (Exception ex)
{
return Status.Failed;
}
}
And the call to SendMessage:
public Status MarketingEmail(OutboundMessage _message)
{
try
{
_message.MessageCreatedDate = System.DateTime.Now;
processor.SendMessage(_message);
return Status.Success;
}
catch (Exception ex)
{
_LOGGER.Log(LoggerLevel.Error, "Error in Marketing Email" + ex.ToString());
return Status.InsertFailed;
}
}
The whole idea is to make a workflow in which sending of the email is the last task and that should be a fire and forget thing.
Now the call to processor.SendMessage(_message) has a suggestion like this:
Because this call is not awaited, execution of the current method
continues before the call is completed. Consider applying the 'await'
operator to the result of the call.
Which is a valid thing since async & await need to be used together.
Questions:
Will the current approach work without any trouble if the suggestion is ignored?
(I am asking this since this is still in the development stage and I can make the suggested design changes now rather than face any critical issues later.)
What is the suggested best practice to design a workflow considering the said requirement?
The current approach will "work" in the sense that it will continue on to return Status.Success; without waiting for the call to processor.SendMessage(_message); to complete.
However, since that call was fired & forgotten, and that SendMessage overload doesn't do any logging in the catch block, you run the risk of emails failing to be sent but nobody getting notified about it.
A common approach for async email sending is this: Stash the email somewhere else (typically a message queue or a database), and then set up a separate async process that reads the queued emails and sends them. If it succeeds, it flags the email as sent. If it fails, it tries again (up to a certain time limit or # of retries), and then if it gives up, it can trigger a notification or set a flag that can be checked later.
Then your code will basically be saying "okay, the email was successfully queued", instead of "okay, the email was sent". Moving the actual sending to a separate process is much more reliable.

Getting email address from text box and send it

if (txtEmail.Text != null)
{
try
{
SmtpClient sc = new SmtpClient("localhost", 587);
sc.Host = "smtp.gmail.com";
sc.Credentials = new NetworkCredential("MyEmail#gmail.com",
"MyPassword");
sc.DeliveryMethod = SmtpDeliveryMethod.Network;
sc.EnableSsl = true;
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("MyEmail#gmail.com");
mailMessage.Subject = "Sending Test";
mailMessage.Body = "this is a test message your UserName is"
+ txtUserName.Text;
mailMessage.IsBodyHtml = true;
string mailBox = txtEmail.Text.Trim();
mailMessage.To.Add(mailBox);
sc.Send(mailMessage);
lblMessage.Text = "Mail send...";
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
else
{
lblMessage.Text = "you should enter your email address";
}
Alright first of all sorry about my weak English language, however i read lots of articles about how to send an E-mail with C# and i know how to do it...
But my problem is when I want to send E-mail that entered to a text box and I put for example
(E-mailAddress.text) into a MailAddress or MailMessage.Add,
it threw me an exception that says
(The parameter 'addresses' cannot be an empty string. Parameter name: addresses)
and shows me the MailAdress or MailMessage object that filled with E-mailAddress.text instead with a string like "abc#yahoo.com" and even in further i'm not capable to send the E-mail ... if there is any help i'd be so glad
First i would change
txtEmail.Text != null
to
!string.IsNullOrEmpty(txtEmail.Text)
Then i would try to do it this way:
mailMessage.To.Add(new MailAddress(txtEmail.Text.Trim()));
instead of
string mailBox = txtEmail.Text.Trim();
mailMessage.To.Add(mailBox);
Also i would implement a method to validated the entered email address to avoid invalid addresses :)
Check for:
if (txtEmail.Text.Trim() != String.Empty)
instead of
if (txtEmail.Text != null)

AutodiscoverLocalException: The Autodiscover service couldn't be located

I want to access exchange server by using .NET 3.5. Here is my code:
class Program
{
static void Main(string[] args)
{
try
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.Credentials = new WebCredentials("email_test#xxx.com", "abcd");
service.AutodiscoverUrl("email_test#xxx.com");
EmailMessage message = new EmailMessage(service);
message.Subject = "Interesting";
message.Body = "The proposition has been considered.";
message.ToRecipients.Add("abc#xxx.com");
message.SendAndSaveCopy();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
I am referring this article to write the codes:
But I receive this exception:
AutodiscoverLocalException: The Autodiscover service couldn't be located.
Anyone can help?
I had this issue and it was due the user account being locked out.
service.Credentials = new WebCredentials("<loginID..not email address>", "< the pw>");
service.AutodiscoverUrl("<your emailaddress>",RedirectionUrlValidationCallback);

Categories