简体   繁体   中英

C# SmtpServer “The operation has timed out”

I have problem in sending mail by smtp and gmail in C# winform application. without attachment sending is successfully but when attachment is added application was thrown to System.Net.Mail.SmtpException and it's message is "The operation has timed out." what's the problem?!

SmtpClient smtpClient = new SmtpClient();
        Attachment att=new System.Net.Mail.Attachment("Path");
        smtpClient.EnableSsl = true;
        smtpClient.Port = 25;
        smtpClient.Timeout = 20000;
        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Host = "smtp.gmail.com";
        smtpClient.Credentials = new System.Net.NetworkCredential
        (from@gmail.com, "password"  );


        System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(from@gmail.com,
            from,
            System.Text.Encoding.UTF8);

        System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress("to@gmail.com");



        MailMessage message = new MailMessage(from, to);
        message.Body = "some text";
        message.BodyEncoding = System.Text.Encoding.UTF8;
        message.Subject = "Subject";
        message.SubjectEncoding = System.Text.Encoding.UTF8;
        message.Bcc.Add(bcc@gmail.com);



        message.Attachments.Add(att);

        try
        {
            smtpClient.Send(message);
        }
        catch (System.Net.Mail.SmtpException ex)
        {
            MessageBox.Show(ex.Message); // The operation has timed out
        }

Edit

i have this problem both of gmail and yahoo!

I don't see any major flaw in your code and I think GMail raised its attachment size limit to 50Mb some time ago... anyway, I suggest you to proceed with the following modifications:

  1. Increase your timeout as much as possible, this alone could solve your problem if you are dealing with very big attachments: smtpClient.Timeout = Int32.MaxValue; .

  2. Try to use different server port. Maybe you have other applications ( Outlook , for example) using the port 25 to communicate and this creates a conflict. Switch to 465 . If it doesn't work, try with 587 .

  3. Try to make a test using a different account.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM