許多開發人員使用.NET通過Gmail的SMTP服務器發送電子郵件。 本指南提供解決方案和工作代碼示例。
>>常見錯誤:“ SMTP服務器需要安全的連接或客戶端未經身份驗證。”
>此錯誤表明您的Gmail SMTP服務器需要身份驗證和安全的連接。
工作代碼示例:
此C#代碼段演示了通過Gmail的SMTP服務器發送成功的電子郵件:
<code class="language-csharp">using System; using System.Net; using System.Net.Mail; namespace EmailSender { class Program { static void Main(string[] args) { // Configure SMTP client var client = new SmtpClient("smtp.gmail.com", 587) { Credentials = new NetworkCredential("[your_email@gmail.com]", "[your_password]"), EnableSsl = true }; // Create email message var message = new MailMessage { From = new MailAddress("[your_email@gmail.com]"), To = { new MailAddress("[recipient_email@example.com]") }, Subject = "Test Email", Body = "Test email body" }; // Send email try { client.Send(message); Console.WriteLine("Email sent successfully!"); } catch (Exception ex) { Console.WriteLine($"Error sending email: {ex.Message}"); } Console.ReadLine(); } } }</code>
重要說明(2021及以後):
中找到此設置。 此步驟對於防止諸如“ 5.5.1認證”之類的身份驗證錯誤至關重要。 考慮使用應用程序密碼來增強安全性而不是常規密碼。
請記住,用您的實際憑據和收件人的電子郵件地址替換,和
以上是為什麼我的.NET GMAIL SMTP電子郵件發送代碼工作?的詳細內容。更多資訊請關注PHP中文網其他相關文章!