I use SendCompletedEventHandler of SmtpClient when sending a list of emails.
The SendCompletedEventHandler is only called when have already sent all emails in the list.
I expexted, that SendCompletedEventHandler is called when an email is sent.
Is there something wrong in my code?
public void SendAllNewsletters(List<string> recipients)
{
string mailText = "My Text";
foreach(string recipient in recipients)
{
//if this loop takes 10min then the first call to
//SendCompletedCallback is after 10min
SendNewsletter(mailText,recipient);
}
}
public bool SendNewsletter(string mailText , string emailaddress)
{
SmtpClient sc = new SmtpClient(_smtpServer, _smtpPort);
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(_smtpuser, _smtppassword);
sc.Credentials = SMTPUserInfo;
sc.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
MailMessage mm = null;
mm = new MailMessage(_senderemail, emailaddress );
mm.IsBodyHtml = true;
mm.Priority = MailPriority.Normal;
mm.Subject = "Something";
mm.Body = mailText ;
mm.SubjectEncoding = Encoding.UTF8;
mm.BodyEncoding = Encoding.UTF8;
//Mail
string userState = emailaddress;
sc.SendAsync(mm, userState);
return true;
}
public void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string)e.UserState;
if (e.Error != null)
{
_news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, false, e.Error.Message);
}
else
{
_news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, true, string.Empty);
}
}
You are creating a new instance of SmtpClient each and every time (and then re-assigning the handler). Use a static variable with a bigger scope.
It works as expected on my machine except that the constructor of MailMessage throw a format exception because "My Tex" is not a valid email address. The first argument is the email address of the sender.
As Josh Stodola points out, you should cache the SmtpClient for the life of this class rather than creating another one for each call. If you don't cache the SmtpClient, then you should add the following line to the end of your SendCompletedCallback (preferably in a finally block):
((SmtpClient)sender).SendCompleted -= SendCompletedCallback;
If this doesn't help you, perhaps you could post more details - such as what is the data in the event args that do get called?
Related
I have this simple code which works for me if i hardcode all the requirements i.e. send/receipent email address etc. but throws exception for if used in Form:
mail.From = new MailAddress(fromtext);
throws ArgumentException was unhandled
The parameter 'address' cannot be an empty string.
Parameter name: address
Complete Code:
private void Form1_Load(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
string FromPass ="******" ;
string fromtext=FromText.Text;
string totext = ToText.Text;
string subject = SubjectText.Text;
string Message = MessageBody.Text;
mail.From = new MailAddress(fromtext); //exception
mail.To.Add(totext);
mail.Subject = subject;
mail.Body = Message;
/* if (fD.FileName != string.Empty)
{
Attachment attachment;
attachment = new Attachment(fD.FileName);
mail.Attachments.Add(attachment);
}*/
SmtpServer.Timeout = 10000;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.Port = 587;
SmtpServer.Credentials = new NetworkCredential(fromtext, FromPass);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Any Suggestions !!!!
I'm not sure why you have placed this code into your Form1_Load Event, as this does not allow the user to enter any data into the form.
What I think you mean to do, is have a submitButton onclick event where you can then check:
if (fromText.Text !="" && ToText.Text !="" &&...)
{
//call a method here to send message, including adding it to body/etc.
//you may want to do further validation checks here too!
}
else
{
MessageBox.Show("Please enter all details","Some credentials Missing");
}
In future, I think you may also benefit from inserting a breakpoint (press F9) to then step slowly through your code (line by line) to see where any errors occur. But in this example, you have just placed your code in the form1_load event (which executes when the form loads, and not after user input).
I want to sent email to 5 different email accounts, my problem is in the following code whenever I active those line of code which has "----> this line" it works fine but when I deactivate those line it sends out five email to one email account and nothing to others.
does any one know what is wrong with my code ?
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
Thread t = null;
MailMessage mailMessage;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//textBox1 is recipients email addresses
String[] to = textBox1.Text.Split(';');
foreach (String s in to)
{
Object[] array = new Object[2];
array[0] = (textBox4.Text.ToString());
array[1] = (s.ToString());
// MessageBox.Show(s.ToString()); -----> this line
t = new Thread(sentEmail);
t.Start(array);
//MessageBox.Show("from: " + array[0].ToString()); -----> this line
// MessageBox.Show("to: " + array[1].ToString()); ----->this line
Thread.Sleep(50);
}
}
void sentEmail(Object array)
{
Object[] o = array as Object[];
SmtpClient client = new SmtpClient();
client.EnableSsl = true;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.Credentials = new NetworkCredential(textBox4.Text, textBox5.Text);
mailMessage = new MailMessage(new MailAddress(o[0].ToString()), new MailAddress(o[1].ToString()));
mailMessage.Body = textBox3.Text;
mailMessage.Subject = textBox2.Text;
client.Send(mailMessage);
}
}
}
You're storing the mailMessage as a property of the Form, and the address is getting changed by another thread before it's actually sent. Adding the MessageBox lets one thread finish befiore another one starts. Just change sentMail to create a new MailMessage instead of reusing the existing one and you should be fine:
public partial class Form1 : Form
{
Thread t = null;
//MailMessage mailMessage; <-- take out this line
void sentEmail(Object array)
{
Object[] o = array as Object[];
SmtpClient client = new SmtpClient();
client.EnableSsl = true;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.Credentials = new NetworkCredential(textBox4.Text, textBox5.Text);
MailMessage mailMessage = new MailMessage(new MailAddress(o[0].ToString()), new MailAddress(o[1].ToString())); // <-- don't use the Form property
mailMessage.Body = textBox3.Text;
mailMessage.Subject = textBox2.Text;
client.Send(mailMessage);
}
You are reusing the mailMessage object. I suspect the lines you have commented out slow the processing down enough that the 5 distinct messages are sent correctly / the thread complete. When they are not there you are getting the weird behaviour as the threads are accessing the same object.
Was going to clean up the code here, but #D_Stanley has you covered.
system.net.mail.smtpclient has two methods for which I am very confused.
1 . SendAsync(MailMessage, Object)
Sends the specified e-mail message to an SMTP server for delivery. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes. -MSDN
2 . SendMailAsync(MailMessage)
Sends the specified message to an SMTP server for delivery as an asynchronous operation. -MSDN
Notice that the names of two methods are different so it is not an overload. What exactly is the difference here?
I am looking for very clear answer as the description given by MSDN for both methods is very ambiguous (at least for me it is.)
The difference is one SendMailAsync uses the new async/await technology and the other uses the old callback technology. And more importantly, the Object that's passed is simply passed into the event handler as the userState when the method completes.
Firstly, they both work asynchronously.
However, SendAsync has existed since .NET 2. In order to maintain backwards compatiblity whilst supporting the new Tasks system SendMailAsync was added.
SendMailAsync returns a Task rather than void and allows the SmtpClient to support the new async and await functionality if required.
//SendAsync
public class MailHelper
{
public void SendMail(string mailfrom, string mailto, string body, string subject)
{
MailMessage MyMail = new MailMessage();
MyMail.From = new MailAddress(mailfrom);
MyMail.To.Add(mailto);
MyMail.Subject = subject;
MyMail.IsBodyHtml = true;
MyMail.Body = body;
MyMail.Priority = MailPriority.Normal;
SmtpClient smtpMailObj = new SmtpClient();
/*Setting*/
object userState = MyMail;
smtpMailObj.SendCompleted += new SendCompletedEventHandler(SmtpClient_OnCompleted);
try
{
smtpMailObj.SendAsync(MyMail, userState);
}
catch (Exception ex) { /* exception handling code here */ }
}
public static void SmtpClient_OnCompleted(object sender, AsyncCompletedEventArgs e)
{
//Get the Original MailMessage object
MailMessage mail = (MailMessage)e.UserState;
//write out the subject
string subject = mail.Subject;
if (e.Cancelled)
{
Console.WriteLine("Send canceled for mail with subject [{0}].", subject);
}
if (e.Error != null)
{
Console.WriteLine("Error {1} occurred when sending mail [{0}] ", subject, e.Error.ToString());
}
else
{
Console.WriteLine("Message [{0}] sent.", subject);
}
}
//
}
//SendMailAsync
public class MailHelper
{
//
public async Task<bool> SendMailAsync(string mailfrom, string mailto, string body, string subject)
{
MailMessage MyMail = new MailMessage();
MyMail.From = new MailAddress(mailfrom);
MyMail.To.Add(mailto);
MyMail.Subject = subject;
MyMail.IsBodyHtml = true;
MyMail.Body = body;
MyMail.Priority = MailPriority.Normal;
using (SmtpClient smtpMailObj = new SmtpClient())
{
/*Setting*/
try
{
await smtpMailObj.SendMailAsync(MyMail);
return true;
}
catch (Exception ex) { /* exception handling code here */ return false; }
}
}
}
SendMailAsync a simple TAP wrapper for SendAsync
More info: Are the SmtpClient.SendMailAsync methods Thread Safe?
This question already has answers here:
Asynchronously sending Emails in C#?
(11 answers)
Closed 9 years ago.
namespace Binarios.admin
{
public class SendEmailGeral
{
public SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
public MailMessage msg = new MailMessage();
public void Enviar(string sendFrom, string sendTo, string subject, string body)
{
string pass = "12345";
System.Net.NetworkCredential smtpCreds = new System.Net.NetworkCredential(sendFrom, pass);
//setup SMTP Host Here
client.UseDefaultCredentials = false;
client.Credentials = smtpCreds;
client.EnableSsl = true;
MailAddress to = new MailAddress(sendTo);
MailAddress from = new MailAddress(sendFrom);
msg.IsBodyHtml = true;
msg.Subject = subject;
msg.Body = body;
msg.From = from;
msg.To.Add(to);
client.Send(msg);
}
}
}
I've this code, but i'd like to improve it in way that i could send mails asynchronous.
Could you suggest any idea to improve this piece of code or other way to do it.
I've tried asynchronous properties that visual studio suggested but couldn't use them.
SmtpClient allows you to send asynchronously, and uses events to notify you when the send completes. This can be unweildy to use, so you can create an extension method to return a Task instead:
public static Task SendAsync(this SmtpClient client, MailMessage message)
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
Guid sendGuid = Guid.NewGuid();
SendCompletedEventHandler handler = null;
handler = (o, ea) =>
{
if (ea.UserState is Guid && ((Guid)ea.UserState) == sendGuid)
{
client.SendCompleted -= handler;
if (ea.Cancelled)
{
tcs.SetCanceled();
}
else if (ea.Error != null)
{
tcs.SetException(ea.Error);
}
else
{
tcs.SetResult(null);
}
}
};
client.SendCompleted += handler;
client.SendAsync(message, sendGuid);
return tcs.Task;
}
To get the result of the send task you can use ContinueWith:
Task sendTask = client.SendAsync(message);
sendTask.ContinueWith(task => {
if(task.IsFaulted) {
Exception ex = task.InnerExceptions.First();
//handle error
}
else if(task.IsCanceled) {
//handle cancellation
}
else {
//task completed successfully
}
});
Wild guess, but SendAsync might do the job!
Change your code from:
client.Send(msg);
To:
client.SendAsync(msg);
more details
link1
link2
I'm having some wierd behaviour in my WinForm application coded in c#.
in my:
private void buttonSave_Click(object sender, EventArgs e)
Im calling my function:
functions.sendStatusEmail();
The weird thing is that, when I press the Save button then email send is not triggered. But if I close my application the mail is handle and sent.
Have I missed something or do one need to trigger som application event manually to have run the sendout.
( I tried using client.SendAsync(mail,null); then it triggerd at click but the mail was empty)
Thanks in advance
--
Edit: code expamples
private void buttonSave_Click(object sender, EventArgs e)
{
// checks if a ticket is active
if (workingTicketId > 0)
{
// update ticket information
functions.updateTicketInfo(workingTicketId, comboBoxPriority.SelectedIndex,
comboBoxStatus.SelectedIndex, textBoxComment.Text);
// gives feedback
labelFeedback.Text = "Updated";
// updates the active ticket list
populateActiveTicketList();
// marks working ticket row in list
dataGridActiveTicketList.Rows[workingGridIndex].Selected = true;
// checks for change of ticket status
if (comboBoxStatus.SelectedIndex != workingTicketStatus)
{
// checks if contact person exists
if (labelContactPersonValue.Text.ToString() != "")
{
// sends email to contact person
functions.sendStatusEmail(labelContactPersonValue.Text, comboBoxStatus.SelectedIndex, workingTicketId, textBoxDescription.Text);
}
// updates working ticket status
workingTicketStatus = comboBoxStatus.SelectedIndex;
}
}
}
and the send email function:
// sends a status email to contact person
// returns noting
public void sendStatusEmail(string email, int newStatus, int ticketId, string ticketText)
{
// defines variables
string emailSubject;
string emailBody;
// some exkluded mailcontent handling
// sends mail
MailMessage mail = new MailMessage("myFromEmail#hidden.com",email,emailSubject,emailBody);
SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["MailSMTP"]);
mail.IsBodyHtml = true;
client.Send(mail);
// dispose
mail.Dispose();
}
Cannot understand why it would not work. I used below function and it sends the email successfully:
public static bool SendEmail (string smtpServer, string fromAddress, string fromDisplayName,
string toAddress, string subject, string contents, bool important) {
MailAddress from = new MailAddress (fromAddress, fromDisplayName);
MailPriority priority = important ? MailPriority.High : MailPriority.Normal;
MailMessage m = new MailMessage {
From = from,
Subject = subject,
Body = contents,
Priority = priority,
IsBodyHtml = false
};
MailAddress to = new MailAddress (toAddress);
m.To.Add (to);
SmtpClient c = new SmtpClient (smtpServer) { UseDefaultCredentials = false };
c.Send (m);
return true;
}
No offence but are you sure that it is closing the application which results in email being sent. Most of the times there is a delay between an email is sent and it is received because of the traffic on SMTP server. Try pressing that button and then wait for some time (3-4 minutes) and try refreshing your inbox during that time.
BTW, the SendAsync didnt work because you called mail.dispose() after the Async call.
The right way to do it in async would be,
private void button1_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage("from#domain.com", "to#domain.com", "subj", "body");
SmtpClient client = new SmtpClient("SMTPHOST");
mail.IsBodyHtml = true;
client.SendCompleted += new
SendCompletedEventHandler(SendCompletedCallback);
client.SendAsync(mail,mail);//send the mail object itself as argument to callback
}
private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled)
{
//Mail sending is cancelled
}
if (e.Error != null)
{
//There is an error,e.Error will contain the exception
}
else
{
//Do any other success processing
}
((MailMessage)e.UserState).Dispose();//Dispose
}