![](/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.