简体   繁体   English

使用 SmtpClient 时“操作超时”

[英]“The operations timed out” when using SmtpClient

I am trying to create a small app using C# framework to send email.我正在尝试使用 C# 框架创建一个小应用程序来发送电子邮件。 However, it does not work.但是,它不起作用。 The app always gives me "The operations timed out."该应用程序总是给我“操作超时”。 I do not why.我不知道为什么。

Here is my code:这是我的代码:

private void button1_Click(object sender, EventArgs e)
   {
     MailAddress fromAddress = new MailAddress("from@gmail.com");
     MailAddress toAddress = new MailAddress("to@gmail.com");

     MailMessage mail = new MailMessage(fromAddress.Address, toAddress.Address);
     mail.Subject = "Testing";
     mail.Body = "contents.";

     SmtpClient client = new SmtpClient();
     client.Host = "smtp.gmail.com";
     client.Port = 587;
     client.EnableSsl = true;
     client.Timeout = 100;
     client.UseDefaultCredentials = false;
     client.Credentials = new NetworkCredential("username", "password");

     try
        {
            client.Send(mail);
            MessageBox.Show("Mail Sent!", "Success", MessageBoxButtons.OK);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
        }

    }

Thanks!谢谢!

Try to set a higher timeout limit.尝试设置更高的超时限制。 It is in milliseconds.它以毫秒为单位。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;

namespace GmailSendTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MailAddress fromAddress = new MailAddress("myusername@gmail.com");
            MailAddress toAddress = new MailAddress("myusername@gmail.com");

            MailMessage mail = new MailMessage(fromAddress.Address, toAddress.Address);
            mail.Subject = "Testing";
            mail.Body = "contents.";

            SmtpClient client = new SmtpClient();
            client.Host = "smtp.gmail.com";
            client.Port = 587;
            client.EnableSsl = true;
            client.Timeout = 10000;
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential("myusername", "mypassword"); 

            try
            {
                client.Send(mail);
                MessageBox.Show("Mail Sent!", "Success", MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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