How can I do a sleep within the while loop? - c#

I am trying to send email every 30 minutes. within a while loop.
while (true)
{
System.Threading.Thread.Sleep(1);
ReadInput();
Application.DoEvents();
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
System.Threading.Thread.Sleep(2000);
mail.From = new MailAddress("");
mail.To.Add("");
mail.Subject = "Test Mail";
mail.Attachments.Add(new System.Net.Mail.Attachment("C://Users//matte//test.txt"));
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("", "");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
System.Threading.Thread.Sleep(10000);
}
I tried an cool-down but the email keeps sending without a sleep. How can I do that. So that the email is sent every 30 minutes?

Sleep function receives amount of time in milliseconds, so it's now waiting right now.
public static void Sleep (int millisecondsTimeout);
Anyway sleep is not the best option you can use, because it blocks the running process. I would use a datetime when the email is sent and compare System.DateTime.Now with this value, so the program continues responding and you can wait just checking if difference between two datetimes is enough time.
DateTime LastSend = System.DateTime.Now;
while (true)
{
if (LastSend.AddMinutes(30) > System.DateTime.Now)
continue;
... your process ...
LastSend = System.DateTime.Now;
}
Hope it helps!

Related

How can i send Mail message in asp .net to Multiple Address (Address,Subject,Body Unique for each mail) at a time

MailMessage msg = new MailMessage();
msg.Body = "";
msg.To.Add(...);
msg.To.Add(...);
SmtpClient smtp = new SmtpClient();
smtp.Send(msg);
This sends the same subject and body to multiple address.
However I want unique mail to be send to each.
Any solution other than looping through?
In the msg.To.Add(...), you will want to add a new MailAddress for each person who will receive the mail message...
foreach(string address in addressList) msg.To.Add(new MailAddress(address))
...
SmtpClient smtp = new SmtpClient();
smtp.Send(msg);
If you have these in a list, then you'll need to split them into a List<string>.
If you make your software that bit more intelligent, you can test to see who's getting what messages and, perhaps, roll them all up into few actual email. Draw yourself a Venn diagram and work it out.
Also, to reduce the size of your message and hide the email address list from other users of your service, you could consider using the Bcc field instead...
foreach(string address in addressList) msg.Bcc.Add(new MailAddress(address))
For unique email address you may have to call Mail function everytime with different email subject etc..
You can use SendEmail(....) with different detail and call it..
Sample
//call function
SendEmail("info#domainname.com", emailSubject, emailBody, isHtml);
public static void SendEmail(string to, string subject, string message, bool isHtml)
{
try
{
// Create a new message
var mail = new MailMessage();
// Set the to and from addresses.
// The from address must be your GMail account
mail.From = new MailAddress("no-reply#domainname.com", "Don't Reply");
mail.To.Add(new MailAddress(to));
// Define the message
mail.Subject = subject;
mail.IsBodyHtml = isHtml;
mail.Body = message;
// Create a new Smpt Client using Google's servers
var mailclient = new SmtpClient();
//mailclient.Host = "smtp.gmail.com";//ForGmail
mailclient.Host = "outlook.office365.com";
mailclient.Port = 587; //ForGmail
// mailclient.Port = 25;
// This is the critical part, you must enable SSL
//mailclient.EnableSsl = true;//ForGmail
mailclient.EnableSsl = true;
mailclient.UseDefaultCredentials = true;
// Specify your authentication details
mailclient.Credentials = new System.Net.NetworkCredential("no-reply#domainname.com", "password");
mailclient.Send(mail);
mailclient.Dispose();
}
catch (Exception ex)
{
}
}

cannot send email using office 365 credentials using C#

I am trying to send email with my office 365 credentials using C#. But It is failing to send and getting exception.
How to fix this? Is it possible to send from office 365?
foreach (var filename in files)
{
String userName = "sri#MyOffice365domain.com";
String password = "password";
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.office365.com");
mail.From = new MailAddress("sri#MyOffice365domain.com");
mail.To.Add("senderaddress#senderdomain.com");
mail.Subject = "Fwd: for " + filename;
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(filename);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(userName, password);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Transaction failed. The server response was: 5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied; Failed to process message due to a permanent exception with message Cannot submit message.
How many emails are you going to send simultaneously?
foreach (var filename in files)
All Outlook APIs accessed via https://outlook.office.com/api or https://outlook.office365.com/api have a limit is 60 requests per minute, per user (or group), per app ID. So, for now, developers only can make limited APIs calls from the app. Read through the Microsoft Blog Post for more details on REST API call limitations.
Try to use the following code instead:
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("someone#somedomain.com", "SomeOne"));
msg.From = new MailAddress("you#yourdomain.com", "You");
msg.Subject = "This is a Test Mail";
msg.Body = "This is a test message using Exchange OnLine";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("your user name", "your password");
client.Port = 587; // You can use Port 25 if 587 is blocked (mine is!)
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
client.Send(msg);
lblText.Text = "Message Sent Succesfully";
}
catch (Exception ex)
{
lblText.Text = ex.ToString();
}

Confirm Sending Email Using C#

when I send email using STMP in C#, I can't make sure that the email has been send although I have used SendCompleted Event Handler. this is my code:
private void btnLogin1_Click(object sender, EventArgs e)
{
try
{
MailAddress FromAddress = new MailAddress("*******", "*******");
MailAddress ToAddress = new MailAddress("*****");
String FromPassword = "******";
SmtpClient SMTP = new SmtpClient();
SMTP.Host = "smtp.yandex.com";
SMTP.Port = 587;
SMTP.EnableSsl = true;
SMTP.DeliveryMethod = SmtpDeliveryMethod.Network;
SMTP.UseDefaultCredentials = false;
SMTP.Credentials = new NetworkCredential(FromAddress.Address, FromPassword);
SMTP.SendCompleted += SMTP_SendCompleted;
MailMessage Message = new MailMessage();
Message.From = FromAddress;
Message.To.Add(ToAddress);
Message.Subject = "Welcome";
Message.SubjectEncoding = Encoding.UTF8;
Message.Priority = MailPriority.High;
Message.IsBodyHtml = true;
Message.Body = "<b>Test Mail</b>";
Message.BodyEncoding = Encoding.UTF8;
SMTP.Send(Message);
}
catch { }
}
private void SMTP_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Sent");
}
}
Thanks in advance.
You need to put some error handling code inside
Catch {...}
Otherwise, you are just catching an error and ignoring it.
If the catch block doesn't fire, then as far as you can be reasonably sure (without checking for a delivery receipt), then you can assume the email has been successfully sent.
If you are using the SendCompleted event, then the email needs sent asynchronously using SendAsync. Otherwise, the method will not return control until after the email is either sent or fails.
In the example you posted, the empty catch is swallowing up any errors that may be occurring to even determine that much.
So either use the SendAsync so that your event gets fired, or actually see if any exceptions are being caught. Empty catch blocks that aren't even catching any specific exception are terrible ideas in nearly every situation. They lead to all sorts of problems.

c# automated email not working [duplicate]

This question already has answers here:
Sending email in .NET through Gmail
(26 answers)
Closed 5 years ago.
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("senttoemailaddress#gmail.com");
mail.To.Add("senttoemailaddress#gmail.com");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("emailaddress.test#gmail.com", "passW0ord");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I'm trying to run the above code to automatically send emails, the code executes up until it reaches smtpServer.send(mail) then it just stops, the email address that I use is valid and the password is valid.
you need to do some configuration in the gmail account before you can send email via gmail
activate 2 steps authentication
enter this link and allow your email to be as SMTP server
i think this will solve the issue .
U have problem with Login\password. I've try your code and get an error:
internal class Program
{
private static void Main(string[] args)
{
try
{
var mail = new MailMessage();
var SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("senttoemailaddress#gmail.com");
mail.To.Add("senttoemailaddress#gmail.com");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new NetworkCredential("emailaddress.test#gmail.com", "passW0ord");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
Console.Write("mail Send");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
...5.5.1 Authentication Required. Learn more at...
Then i just change login\password to my and it works:
mail Send
Try with SMTP port: 465
Notice :
Google limits the amount of mail a user can send, via its portable SMTP server. This limit restricts the number of messages sent per day to 99 emails; and the restriction is automatically removed within 24 hours after the limit was reached.

Sending Email asynchronously in ASP.NET C#

I was wondering if theres a way to send email asynchronously in asp.net c#. I've used the following code to send the emails:
if (checkObavijest.Checked)
{
List<hsp_Kupci_Newsletter_Result> lista = ServisnaKlasa.KupciNewsletter();
for (int i = 0; i < lista.Count; i++)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("*******");
mail.To.Add(lista[i].Email);
mail.Subject = "Subject";
mail.SubjectEncoding = Encoding.UTF8;
mail.BodyEncoding = Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
mail.Body = "Some message";
SmtpClient smtpClient = new SmtpClient();
Object state = mail;
smtpClient.Credentials = new NetworkCredential("****#gmail.com", "****");
smtpClient.Port = 587;
smtpClient.Host = "smtp.gmail.com";
smtpClient.EnableSsl = true;
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
try
{
smtpClient.SendAsync(mail, state);
}
catch (Exception ex)
{
}
}
void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
MailMessage mail = e.UserState as MailMessage;
if (!e.Cancelled && e.Error != null)
{
string poruka = "Emailovi poslani!";
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + poruka + "');", true);
}
}
But when I tick the option for sending emails, the page loads like 40 seconds, then after 40 seconds emails are sent then. As you can see I'm pulling out like 20-30 emails currently out of my DB. I thought this was the correct way to send mails asynchronously, but apparently its not... How can I push the email sending to another thread so it doesn't affects the user who is using this page? Can someone help me out with this ? Thanks !
The reason is mentioned here on the MSDN documentation on SmtpClient.SendAsync
After calling SendAsync, you must wait for the e-mail transmission to
complete before attempting to send another e-mail message using Send
or SendAsync.
You could call SendAsync using ThreadPool thru a wrapped method call. This would give you something like a fire-and-forget scenario.
Something like this:
public void SendViaThread(System.Net.Mail.MailMessage message) {
try {
System.Threading.ThreadPool.QueueUserWorkItem(SendViaAsync, message);
} catch (Exception ex) {
throw;
}
}
private void SendViaAsync(object stateObject) {
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
System.Net.Mail.MmailMessage message = (MmailMessage)stateObject;
...
smtp.Credentials = new NetworkCredential("...");
smtp.Port = 587;
smtp.Host = "...";
...
smtp.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
...
smtp.Send(message);
}
And you would call SendViaThread(mail) in your code. So, your loop now becomes:
for (int i = 0; i < lista.Count; i++) {
MailMessage mail = new MailMessage();
mail.From = new MailAddress("...");
mail.To.Add(lista[i].Email);
mail.Subject = "...";
...
mail.Body = "...";
SendViaThread(mail);
}
If you want to not have your main thread waiting, try tossing it in a Task.
Task.Factory.StartNew( () => {
// do mail stuff here
});
Be aware, though that each time you spawn a task, it'll spawn a new (or re-use) a thread that your system has made. If you're firing off 30 e-mails, you have the potential of firing off a lot of threads (the system has a programmable cap, too). Task.Factory.StartNew is a very simple way to do a fire-and-forget process.
http://msdn.microsoft.com/en-us/library/dd321439%28v=vs.110%29.aspx
(in this example, the code is also keeping a collection of Tasks, which is nice if you care to manage them -- but in reality, you only need the Task.Factory.StartNew(()=>{ bit if you want to fire-and-forget. Just be careful because you don't want to have orphaned threads pegging your memory usage.

Categories