我有这段代码发送电子邮件,但每次执行时,我都会收到此异常
等待操作期限已过期
public static void CreateTimeoutTestMessage(string server)
{
string to = "touilhaythem1@gmail.com";
string from = "raddaouirami@gmail.com";
string subject = "Using the new SMTP client.";
string body = @"Using this new feature, you can send an e-mail message from an application very easily.";
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient(server, 587);
client.EnableSsl = true;
client.Credentials=new NetworkCredential("raddaouirami@gmail.com", "XXXXXXXXX");
Console.WriteLine("Changing time out from {0} to 100.", client.Timeout);
client.Timeout = 100;
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTimeoutTestMessage(): {0}",
ex.ToString());
}
Console.ReadLine();
}
答案 0 :(得分:0)
当然你会超时 - 你为超时指定了100毫秒。这很短暂。联系服务器并发送邮件可能需要超过100毫秒。尝试像10000毫秒这样的东西十秒钟。
我知道你复制并粘贴的MSDN sample,但它太短了。最好删除以下行:
Console.WriteLine("Changing time out from {0} to 100.", client.Timeout);
client.Timeout = 100;
请尝试这个(从here获得想法):
...
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient(server, 587);
client.EnableSsl = true;
client.UseDefaultCredentials = false; // <--- NEW
client.Credentials = new NetworkCredential("raddaouirami@gmail.com", "XXXXXXXXX");
它可能会等待身份验证。
答案 1 :(得分:0)
你在哪里:
SmtpClient client = new SmtpClient(server, 587);
将其分解为:
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
因为我不知道您在哪里定义了服务器,并且如果您尝试使用gmail,您可以将其声明为主机,以确定这是否让您更接近目标
另外注意,gmail smtp不允许您更改发送地址,以防止网络钓鱼,因此如果您计划允许输入更改from变量,它将无法正常工作,gmail默认为凭证中提供的电子邮件