-1

I am sending an email with some attachments and some basic information. So every thing is sending perfectly. But when ever i check my inbox mail not yet there, So i tried closing my application form. So that time mail came.

So tired a lot of time and i found that when ever i send the mail and closing my entire form that time email is received in the recipient mailbox. Any ideas!!!

code snippet:

 SmtpClient smtp = new SmtpClient(smtpserver, 25);

            MailMessage msg = new MailMessage();

            msg.From = new MailAddress(email_From);
            msg.To.Add(email_Recipient);

            msg.IsBodyHtml = true;
            msg.Subject = email_Subject;

            ///Attachment's and Body


            try
            {
                    _f3.ShowDialog();
                    smtp.Send(msg);
                    MessageBox.Show("Email Successfully Sent!!!", "Mail!!!.");
                    Environment.Exit(0);// -->> if i keep this mail is going.. else i have to close
                    // my application to receive mail
            }

            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }   
Stacy Kebler
  • 180
  • 1
  • 3
  • 22
  • 1
    I had this issue before. If I remember correctly, I had to dispose the `SmtpClient` when I was done. – TyCobb Oct 03 '14 at 15:38
  • 1
    What version of .NET are you targeting? (The C# compiler in VS2010 supports multitargeting) See http://stackoverflow.com/a/2782559/103167 – Ben Voigt Oct 03 '14 at 17:41
  • @BenVoigt i tried this also wont work... `using (smtp as IDisposable) { smtp.Send(msg); } ` – Stacy Kebler Oct 03 '14 at 17:57
  • Theory... since your comment makes it look like you are attaching files, make sure you dispose of everything possible. It could very well be that something is leaving the file locked and the message cannot send until it is freed -- hence the reason why it sends once your application is closed. DISPOSE! :D – TyCobb Oct 03 '14 at 18:24

4 Answers4

2

As @TyCobb points out, SmtpClient in .NET 4+ implements IDisposable. You're breaking its contract by not calling smtp.Dispose(). A using block is often the most convenient way to accomplish that.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • `Error System.Net.Mail.SmtpClient' does not contain a definition for 'Dispose' and no extension method 'Dispose' accepting a first argument of type 'System.Net.Mail.SmtpClient' could be found (are you missing a using directive or an assembly reference?)` – Stacy Kebler Oct 03 '14 at 17:23
  • 2
    @StacyKebler: [MSDN says it is there](http://msdn.microsoft.com/en-us/library/ee706941%28v=vs.110%29.aspx). And also explains why it is important to call Dispose. If it isn't as public as MSDN says, then try `((IDisposable)smtp).Dispose()`. Or just go with `using`, as I said. – Ben Voigt Oct 03 '14 at 17:39
  • `unable to cast object of type' system.net.mail.smptclient' to type ' system.idisposable'` – Stacy Kebler Oct 03 '14 at 17:51
  • @StacyKebler As Ben asked in the question comments, what version of .NET are you running? `SmtpClient` didn't implement `IDisposable` until 4.0. `MailMessage` implemented `IDisposable` in 2.0, but I doubt calling it will actually fix your issue. It's something to just try though. – TyCobb Oct 03 '14 at 18:14
2

So, there are loads of ways to send an email. and the Using statement is a very popular one.

Here is a link to another method of sending a mail: Send e-mail via SMTP using C#

I suppose a question to you is, what are you trying to do?

Is this a large scale email sender? You may want to use a mail dispatch service, e.g. sendgrid.

If this is a test project for yourself of it is going to send low priority admin emails or something, you may be fine with the above.

In any case though, I would have a class setup where you can pass in the following: To, From, Subject, HTMLMessageContent, PlainTextMessageContent, at minimum.

This method would then process all email sending from your application. The below is a good starting point.

public bool SendMail(string from, string to, string subject, string htmlContent, string plainContent)
{
    //Email sending code - could be replaced by 3rd party mail sending API, etc.
    MailMessage mail = new MailMessage(from, to);
    SmtpClient client = new SmtpClient();
    client.Port = 25;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.Host = "smtp.google.com";
    mail.Subject = subject;
    mail.Body = htmlContent;
    client.Send(mail);
}

You would then call the above by

//... code
SendMail(email_From, email_Recipient, email_Subject, email_body_HTML, email_body, plaintext);
//... code

Obviously, you can then do things like returning a bool indicating success, error handling/catching/logging, attachments etc.

Give this a try and see if it is a good starting place.

Alternatively, the below links should be of some use: http://csharp.net-informations.com/communications/csharp-smtp-mail.htm Sending email in .NET through Gmail

Community
  • 1
  • 1
Del
  • 416
  • 2
  • 13
1

try re-arraging your code:

 smtp.Send(msg);
_f3.ShowDialog();

put the line that sends the email above the line where you show the modal dialog box. Your code will not continue until this form is closed.

oGJo
  • 144
  • 8
1

Try using a "using block" and maybe too, Show() insted ShowDialog()

using(SmtpClient smtp = new SmtpClient(smtpserver, 25))
{

        MailMessage msg = new MailMessage();

        msg.From = new MailAddress(email_From);
        msg.To.Add(email_Recipient);

        msg.IsBodyHtml = true;
        msg.Subject = email_Subject;

        ///Attachment's and Body


        try
        {
                _f3.ShowDialog(); //until you dont close the dialog, it will not send the msg. Maybe _f3.Show() solve your problem
                smtp.Send(msg);
                MessageBox.Show("Email Successfully Sent!!!", "Mail!!!.");
                //Environment.Exit(0);// -->> if i keep this mail is going.. else i have to close
                // my application to receive mail
        }

        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }   
}
paio
  • 167
  • 4
  • `Error 'System.Net.Mail.SmtpClient': type used in a using statement must be implicitly convertible to 'System.IDisposable'` – Stacy Kebler Oct 03 '14 at 19:23
  • when i used `using(SmtpClient smtp = new SmtpClient(smtpserver, 25))` its howed me the above eror – Stacy Kebler Oct 03 '14 at 19:23
  • 1
    If you are using FrameWork < 4, dont use the using block cause SmtpClient is not IDisposable. – paio Oct 03 '14 at 19:47
  • holy mother of god!! i went to Project Properties -> Application Tab. and changed the frame work from 2.0 to ver 4.0.. noe my `smtp.Dispose();` is working perfectly.. i mean when i change the frame work.. do this affect my application.. because i need this application to work on a windows XP professional OS – Stacy Kebler Oct 03 '14 at 20:01
  • also, i wanted to point out that this application is running in two different computer in server. so is there any problem. i can see one more frame work called `.Net framework 4 Client profile`.. do i need to select that.. if i am running this application on a network domain.. – Stacy Kebler Oct 03 '14 at 20:04