许多开发人员使用.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中文网其他相关文章!