C# 使用 SmtpClient 时“操作超时”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13165396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:50:12 来源:igfitidea点击:
"The operations timed out" when using SmtpClient
提问by YU FENG
I am trying to create a small app using C# framework to send email. However, it does not work. The app always gives me "The operations timed out." I do not why.
我正在尝试使用 C# 框架创建一个小应用程序来发送电子邮件。但是,它不起作用。该应用程序总是给我“操作超时”。我不知道为什么。
Here is my code:
这是我的代码:
private void button1_Click(object sender, EventArgs e)
{
MailAddress fromAddress = new MailAddress("[email protected]");
MailAddress toAddress = new MailAddress("[email protected]");
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!
谢谢!
采纳答案by Imre Greilich
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("[email protected]");
MailAddress toAddress = new MailAddress("[email protected]");
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);
}
}
}
}

