簡體   English   中英

無法從ASP.NET向客戶端發送電子郵件

[英]Can`t send email to client from ASP.NET

我做了一個測試頁面,其中有一個用於電子郵件地址的文本框,一個提交按鈕和一個錯誤標簽。

這是我在論壇上看到的C#代碼:

try
{
    MailMessage mail = new MailMessage("danielohayon2014@gmail.com", (string)txtEmail.Text);
    SmtpClient client = new SmtpClient();
    client.Port = 25;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.Host = "smtp.google.com";
    mail.Subject = "this is a test email.";
    mail.Body = "this is my test email body";
    client.Send(mail);

    lblError.Text = "Message sent!";
}
catch (Exception ex)
{
    lblError.Text = ex.ToString();
}

它顯示給我的完整錯誤是:

System.Net.Mail.SmtpException:發送郵件失敗。 ---> System.Net.WebException:無法解析遠程名稱:System.Net.ServicePoint.GetConnection(PooledStream PooledStream,對象所有者,布爾異步,IPAddress&地址,Socket&abortSocket,Socket& System.Net.PooledStream.Activate(對象owningObject,布爾異步,GeneralAsyncDelegate asyncCallback)處的System.Net.PooledStream.Activate(Object owningObject,GeneralAsyncDelegate asyncCallback)的System.Net.ConnectionPool.GetConnection(Object owningObject,GeneralAsyncDelegate asyncCallback, System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)在System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)在System.Net.Mail.SmtpClient.GetConnection()在System.Net.Mail處的Int32 creationTimeout)。 SmtpClient.Send(MailMessage消息)-內部異常堆棧跟蹤的結尾-在System.Net.Mail.SmtpClient.Send(MailMessage消息)在d:\\ WebDev \\中的email.btnSend_Click(Object sender,EventArgs e)測試\\ email.aspx .cs:第28行

但這對我不起作用,我不知道該怎么做才能幫助我!

您的主機名和端口不正確smtp.google.com使用smtp.gmail.com而不是smtp.google.com ,端口是587而不是25。

您的代碼也沒有提供任何網絡憑據。 您已將UseDefaultCredentials正確設置為false,但是還需要提供新的NetworkCredentials。

client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");

您還需要啟用SSL:

client.EnableSsl = true;

您可以通過添加以下內容在web.config中設置所有Smtp客戶端的憑據

<system.net>
    <mailSettings>
        <smtp deliveryMethod="Network" from="no-reply@yourdomain.com">
                <network host="smtp.host.net" userName="yourUsername" password="yourPassword" port="587" enableSsl="true" />
        </smtp>
    </mailSettings>
</system.net>

然后,您發送電子郵件的代碼變得更加簡單

try
{
    using (var client = new SmtpClient())
    {
        MailMessage mail = new MailMessage("MyEmail@gmail.com", (string)txtEmail.Text);
        mail.Subject = "this is a test email.";
        mail.Body = "this is my test email body";
        client.Send(mail);
    }

    lblError.Text = "Message sent!";
}
catch (Exception ex)
{
    lblError.Text = ex.ToString();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM