gpt4 book ai didi

c# - 使用 C# 通过 Gmail SMTP 服务器发送电子邮件

转载 作者:IT王子 更新时间:2023-10-29 03:29:04 24 4
gpt4 key购买 nike

出于某种原因,对于“Sending email in .NET through Gmail ”,接受的答案和任何其他答案都不适合我。为什么它们不起作用?

更新:我已经尝试了另一个问题中的所有答案(接受的和其他的),但没有一个有效。

我只想知道它是否适用于其他人,否则 Google 可能已经改变了一些东西(以前发生过)。

当我尝试使用 SmtpDeliveryMethod.Network 的代码片段时,我很快收到 SmtpException on Send(message)。消息是

The SMTP server requires a secure connection or the client was not authenticated.

服务器响应是:

5.5.1 Authentication Required. Learn more at" <-- seriously, it ends there.

更新:

这是我很久以前问过的问题,接受的答案是我在不同项目中多次使用的代码。

我采用了这篇文章和其他 EmailSender 项目中的一些想法来创建一个 EmailSender project at Codeplex .它专为可测试性而设计,支持我最喜欢的 SMTP 服务,例如 GoDaddy 和 Gmail。

最佳答案

CVertex,请务必检查您的代码,如果没有发现任何问题,请将其发布。我只是在我正在处理的测试 ASP.NET 站点上启用了它,并且它有效。

实际上,在某些时候我的代码出现了问题。直到我在控制台程序上有一个更简单的版本并看到它正在运行时,我才发现它(您担心的 Gmail 端没有变化)。下面的代码就像您提到的示例一样工作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("myusername@gmail.com", "mypwd"),
EnableSsl = true
};
client.Send("myusername@gmail.com", "myusername@gmail.com", "test", "testbody");
Console.WriteLine("Sent");
Console.ReadLine();
}
}
}

我还使用 web.config、http://msdn.microsoft.com/en-us/library/w355a94k.aspx 的组合让它工作和代码(因为在配置文件中没有匹配的 EnableSsl :( ).

2021 年更新

默认情况下,您还需要在您的 Gmail 设置页面中启用对“不太安全的应用程序”的访问:google.com/settings/security/lesssecureapps。如果您收到异常“`服务器响应是:需要 5.5.1 身份验证”,这是必需的。 – 感谢@Ravendarksky

关于c# - 使用 C# 通过 Gmail SMTP 服务器发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/704636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com