![](/img/trans.png)
[英]ASP.Net C# Application does not send e-mails without default credentials
[英]Can we send mails from localhost using asp.net and c#?
我正在using System.Net.Mail;
和以下代码发送邮件
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
// Set the sender's address
message.From = new MailAddress("fromAddress");
// Allow multiple "To" addresses to be separated by a semi-colon
if (toAddress.Trim().Length > 0)
{
foreach (string addr in toAddress.Split(';'))
{
message.To.Add(new MailAddress(addr));
}
}
// Allow multiple "Cc" addresses to be separated by a semi-colon
if (ccAddress.Trim().Length > 0)
{
foreach (string addr in ccAddress.Split(';'))
{
message.CC.Add(new MailAddress(addr));
}
}
// Set the subject and message body text
message.Subject = subject;
message.Body = messageBody;
// Set the SMTP server to be used to send the message
client.Host = "YourMailServer";
// Send the e-mail message
client.Send(message);
对于主机,我提供client.Host = "localhost";
为此它错误地下降
无法建立连接,因为目标机器主动拒绝了
当我使用client.Host = "smtp.gmail.com";
我收到以下错误
连接尝试失败,因为连接方在一段时间后没有正确响应,或者因为连接的主机没有响应而建立连接失败
我无法通过本地主机发送邮件。 请帮帮我,我是 C# 新手,请在我出错的代码中纠正我..?
这是一些用于通过 gmail 发送邮件的代码(来自 stackoverflow 上某处的代码。它类似于此处的代码: Gmail:如何以编程方式发送电子邮件):
using (var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("yourmail@gmail.com", "yourpassword"),
EnableSsl = true
})
{
client.Send("frommail@gmail.com", "tomail@gmail.com", "subject", message);
}
要从client.Host = "localhost"
发送邮件,您需要设置本地 SMTP 服务器。
要通过 Google(或通过任何其他 SMTP 服务器,包括您自己的本地 SMTP)发送邮件,您必须设置用户名、密码、ssl 设置 - 所有这些都是所选 SMTP 服务器的要求,您需要阅读他们的帮助。
例如,Google 说您需要 SSL、端口 465 或 587、服务器smtp.gmail.com
以及您的用户名和密码。
您可以在 .config 文件中分配所有这些值。
<system.net>
<mailSettings>
<smtp>
<network host="smtp.gmail.com" enableSsl="true" port="587" userName="yourname@gmail.com" password="password" />
</smtp>
</mailSettings>
</system.net>
或者在每次使用前在代码中设置为 SmtpClient:
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSSL = true;
client.Credentials = new NetworkCredential("yourname@gmail.com", "password");
将此代码放在 web.config 文件中的<configuration> </configuration>
中
<system.net>
<mailSettings>
<smtp>
<network host="smtp.gmail.com" enableSsl="true" port="587" userName="youremail@gmail.com" password="yourpassword" />
</smtp>
</mailSettings>
</system.net>
然后后端代码
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.From = new MailAddress("email@gmail.com");
message.To.Add(new MailAddress(TextBoxEadd.Text));
message.CC.Add(new MailAddress("email@gmail.com"));
message.Subject = "New User Registration ! ";
message.Body = "HELLO";
sr.Close();
SmtpClient client = new SmtpClient();
client.Send(message);
我希望这段代码对你有帮助! :)
使用这条线..不要使用端口和主机名
LocalClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
我只想补充一点,Gmail 现在需要应用密码才能从其他应用程序中使用它。 检查此链接。 我不得不以艰难的方式找到它。 创建应用程序密码后,我更改了 NetworkCredentials 以使用它来发送电子邮件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.