How to resolve "The operation has timed out."? - c#

I'm trying to send email using C# code, email was sent when I send it to single person but it is not getting sent when I send it to multiple persons. and getting an error "The operation has timed out." I'm not getting the reason behind it. Please help to find the reason.
Code:
public string SendEmail(List<string> ToEmailAddresses,string body, string emailSubject)
{
var smtp = new SmtpClient { DeliveryMethod = SmtpDeliveryMethod.Network };
smtp.Host = "xyz-host-name";
smtp.Port = 25;
smtp.EnableSsl = false;
var fromAddress = new MailAddress(ConfigurationManager.AppSettings["MailUserName"], "Rewards and Recognition Team");
using (var message = new MailMessage() { Subject = emailSubject, Body = body })
{
message.From = fromAddress;
foreach (string email in ToEmailAddresses)
{
message.To.Add(email);
}
message.IsBodyHtml = true;
try
{
_logger.Log("EmailService-SendEmail-try");
smtp.Send(message);
return "Success";
}
catch (Exception ex)
{
_logger.Log("EmailService-SendEmail-" + ex.Message);
return "Error";
}
}
}

Whenever you're attempting to do anything which may take some time, it's always best practice to run it in a separate thread or use an asynchronous method.My recommendation would be to use the SmtpClient.SendAsync method. To do this, change:
public string SendEmail(List<string> ToEmailAddresses, string body, string emailSubject)
to:
public async string SendEmail(List<string> ToEmailAddresses, string body, string emailSubject)
and include await smtp.SendAsync(...) rather than smtp.Send(...). This will allow further execution of the UI thread whilst sending the mail and not make the application grey out with the "not responding" message.To read more about smtp.SendAsync(...) including parameters and remarks, take a look at the MSDN documentation regarding the method.

Related

How to know, that email was sent, and attachments can be deleted?

I have a method, which saves screenshot by the definite path and then makes email message, attaching screenshot to it. As I've understood, after sending it - the special thread is being created in which attachment file is used, so I can't delete it while that thread is working. So, I need to know if when the file will be accessible for deleting.
Here's my code:
-- Configuring smtp
private SmtpClient CreateSMTP()
{
var smtp = new SmtpClient("gate");
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("notifications#****.com", "3eCMCQxFde");
smtp.Port = 25;
smtp.EnableSsl = false;
return smtp;
}
-- Making message
public MailMessage MakeMessage(bool screenshotFlag)
{
MailAddress from = new MailAddress("notifications#****.com", Name);
MailAddress to = new MailAddress("****#****.com");
MailMessage message = new MailMessage(from, to);
message.Subject = Subject == string.Empty ? string.Empty : Subject;
message.Body = MessageText;
message.Body = GenerateLogAndExceptionInfo(message.Body);
message.BodyEncoding = Encoding.Unicode;
message.ReplyTo = new MailAddress(Mail);
if (screenshotFlag)
{
CreateScreenshot();
message.Attachments.Add(new Attachment(MailHelper.FeedBackScreenShotPath));
}
return message;
}
-- Sending email
public void SendMessage()
{
using (SmtpClient smtp = CreateSMTP())
{
smtp.Send(MakeMessage(SendWithScreenshot));
}
}
From the documentation:
These methods block while the message is being transmitted.
So while the message is being transmitted, the method blocks. So after the method is done and you've disposed the message instance, you could delete the file.
Of course, it could still have a lock on the file. That is why I would say you should first dispose the SmtpClient and then try to delete the file (so do that after the using block). It should be fine then.
I've seen that the file was holding by the message object, not by smtp object, so I added using block for message, too.
Thanks to all))

ASP.NET Send email with Parallels Plesk Panel 11.5

I'd like to create a web application in ASP.NET C# MVC 5 using Parallels Plesk Panel 11.5 using HostGator.
Is that possible? I'd like my web app to send an email whenever someone fills out a particular form. Where can I go to find out the SMTP server information? What do I need to know to set that up?
I'd appreciate any other help, links, or guides you can provide as I set this up.
Thank you.
This is might be too late but to help the others;
public static void SendEmail(string toEmail, string subject, string body)
{
try
{
const string fromEmail = "yourEmail#YourDomain.com";
var message = new MailMessage
{
From = new MailAddress(fromEmail),
To = { toEmail },
Subject = subject,
Body = body,
DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
};
using (SmtpClient smtpClient = new SmtpClient("webmail.YourDomain.com"))
{
smtpClient.Credentials = new NetworkCredential("yourEmail#YourDomain.com", "your email password");
smtpClient.Port = 25;
smtpClient.EnableSsl = false;
smtpClient.Send(message);
}
}
catch (Exception excep)
{
//ignore it or you can retry .
}
}
This worked for me on Plesk Onyx 17.5.3

Doubts on sending more than one email asynchronously in MVC3

In my application I have a functionality to save and publish articles. So when I click on "Save and Publish" button three things happened:
Published articles get saved in database.
A Notification email goes to a group of users that a new articles is available.
After sending emails page get redirect to "Article Listing" page without showing any success or failure message for an email.
Now Number of users who will receive emails can vary say for e.g 10, 30 50 and so on. I want to send notification emails asynchronously so that page won't get block until all the mails doesn't go to their receptionists.
Given below is a piece of code from "PublishArticle" action method
foreach (string to in emailIds)
{
ArticleNotificationDelegate proc = Email.Send;
IAsyncResult asyncResult = proc.BeginInvoke(subject, body, to, from, cc, null, null, null);
}
Below I have defined a delegate to invoke Send method
private delegate bool ArticleNotificationDelegate (string subject, string body, string to, string from, string cc, string bcc = null);
and this is the code to send an email:
public static bool Send(string subject, string body, string to, string from, string cc, string bcc = null)
{
bool response;
MailMessage mail = new MailMessage();
MailAddress fromAddress = new MailAddress(from);
mail.To.Add(to);
if (!string.IsNullOrWhiteSpace(cc))
{
mail.CC.Add(cc);
}
if (!string.IsNullOrWhiteSpace(bcc))
{
mail.Bcc.Add(bcc);
}
mail.From = fromAddress;
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
try
{
client.Send(mail);
response = true;
}
catch (Exception)
{
response = false;
}
finally
{
client.Dispose();
mail.Dispose();
}
return response;
}
Although this code is working fine but still I want to know that whether my this approach is fine and will not cause any problem in future.
If there is a better approach to accomplish my objective then please suggest me.
Note: As I am using .net framework 4.0 so cannot use the new features of Asyn and await available in 4.5.
Also I had used method client.SendAsync by simply replacing the client.Send and rest of my code in above Send method was same. After this change NO mails were being send and also it did not throw any exception. So I did not go with this change.
I want to send notification emails asynchronously so that page won't get block until all the mails doesn't go to their receptionists.
That's a very dangerous approach, because ASP.NET will feel free to tear down your app domain if there are no active requests. ASP.NET doesn't know that you've queued work to its thread pool (via BeginInvoke). I recommend that you use a solution like HangFire to reliably send email.

HTML based email not working properly in asp.net web form

I am working on web form which collects certain user information from users and sends confirmation by email. I am trying to user the following approach to send the HTML email as it make managing HTML based email easy.
https://gist.github.com/1668751
I made necessary changes to the code but it is not working. I read other related article to make it work but i am doing something wrong.
Following line of code generates error The replacements dictionary must contain only strings.
MailMessage msgHtml = mailDef.CreateMailMessage(to, replacements, MessageBody, new System.Web.UI.Control());
I have made many change to the code but it doesnt seem to work for me. I would appreciate help to make this code work.
If i comment the above line of code with some other changes then i can send email but i can't replace the token. Any easy approach to replace token is also welcome.
Below is the Complete code i am using right now
String to, subject, Name;
subject = "Booking Confirmation";
Name = txtName.text;
ListDictionary replacements = new ListDictionary();
replacements.Add("<%Name%>", Name);
replacements.Add("<%Email%>", objVR.Email);
replacements.Add("<%CompanyName%>", objVR.CompanyName);
replacements.Add("<%BookingDate%>", objVR.BookingDate);
replacements.Add("<%BookingTime%>", objVR.TimeSlot);
replacements.Add("<%NoOfVisitors%>", objVR.NoOfVisitors);
replacements.Add("<%BookingCode%>", objVR.BookingUniqueID);
MailDefinition mailDef = new MailDefinition();
string MessageBody = String.Empty;
string filePath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
using (StreamReader sr = new StreamReader(filePath + #"\en\VREmailEnglish.htm"))
{
MessageBody = sr.ReadToEnd();
}
MailMessage msgHtml = mailDef.CreateMailMessage(to, replacements, MessageBody, new System.Web.UI.Control());
string message = msgHtml.Body.ToString();
Helper.SendTokenEmail(to, subject, msgHtml, isHtml);
public static void SendTokenEmail(string to, string subject, string mailMessage, bool isHtml)
{
try
{
// Create a new message
var mail = new MailMessage();
// Set the to and from addresses.
mail.From = new MailAddress("noreply#somedomain.net");
mail.To.Add(new MailAddress(to));
// Define the message
mail.Subject = subject;
mail.IsBodyHtml = isHtml;
mail.Body = mailMessage.ToString();
//Object userState = mailMessage;
// Create a new Smpt Client using Google's servers
var mailclient = new SmtpClient();
mailclient.Host = "mail.XYZ.net";
//mailclient.Port = 587; //ForGmail
mailclient.Port = 2525;
mailclient.EnableSsl = false;
mailclient.UseDefaultCredentials = true;
// Specify your authentication details
mailclient.Credentials = new System.Net.NetworkCredential("noreply#somedomain.net", "XYZPassword");
mailclient.Send(mail);
mailclient.Dispose();
}
catch (Exception ex)
{
}
}
As pointed out by HatSoft the ListDictionary accepts objects as key and value so this looks like it should work.
But reading the docs for the CreateMailMessage() method here http://msdn.microsoft.com/en-us/library/0002kwb2.aspx indicates you need to convert the value to a string otherwise it will throw an ArgumentException.
So to fix make sure all values you add to the ListDictionary are converted to string i.e
objVR.BookingDate.ToString()

SMTP Mail does not sends for the second call

Here is the code which calls the sendmail method. The problem is that only the first call of sendmail sends the mail to the receiver. The second time when sendmail is called , it gets executed perfectly but never delivers any mail. If I put the application in debug mode and then execute it step by step both the mails get delivered. It seemed like the execution speed of the program is so fast that something goes wrong. Therefore I kept a delay below send function, so it started working fine for me, But I don't think it is a perfect solution. Anybody has any clue what is going on here.
if (!String.IsNullOrEmpty(SendMailAdmin))
{
SendMail(SendMailFrom, SendMailAdmin, Subject, AdminMessageText + "<br>" + MessageText);
}
if (!String.IsNullOrEmpty(SendMailOwner))
{
SendMail(SendMailFrom, SendMailOwner, Subject, OwnerMessageText + "<br>" + MessageText);
}
public void SendMail(String MessageFrom, String MessageTo, String MessageSubject, String MessageBody)
{
MailMessage Message = new MailMessage();
Message.Priority = MailPriority.High;
Message.From = new MailAddress(MessageFrom);
Message.To.Add(MessageTo);
Message.Subject = MessageSubject;
Message.IsBodyHtml = true;
Message.Body = MessageBody;
try
{
SmtpClient client = new SmtpClient(SMTPServer, Convert.ToInt32(SMTPPort));
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("{myusername}", "{mypassword}");
client.Send(Message);
System.Threading.Thread.Sleep(3000);
}
catch
{
throw;
}
}
I personally think the only thing that'll work for you at this point is the delay code .#Shadow is right , this is how servers are configured

Categories