smtp异常“发送邮件失败”

smtp exception “failure sending mail”

我创建了用于发送电子邮件的控制台应用程序

    public static void sendEmail(string email, string body)
    {
        if (String.IsNullOrEmpty(email))
            return;
        try
        {
            MailMessage mail = new MailMessage();
            mail.To.Add(email);
            mail.From = new MailAddress("test@gmail.com");
            mail.Subject = "sub";

            mail.Body = body;

            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
            smtp.Credentials = new System.Net.NetworkCredential("test@gmail.com", "admin@1234"); // ***use valid credentials***
            smtp.Port = 587;

            //Or your Smtp Email ID and Password
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }
        catch (Exception ex)
        {

        }
    }

我使用的是我的 Gmail 帐户的正确凭据。

我需要为 GMail 帐户 设置什么设置吗?

很可能您实际上遇到了这个错误,它只是通过您在控制台应用程序中以某种方式被抑制了。

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

更改这段代码并添加一行。它在凭据之前很重要。

smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
// ** HERE! **
smtp.UseDefaultCredentials = false;
// ***********
smtp.Credentials = new System.Net.NetworkCredential("test@gmail.com", "admin@1234"); // ***use valid credentials***
smtp.Port = 587;

您还需要转到此处并启用安全性较低的应用程序。

https://www.google.com/settings/security/lesssecureapps

或者,如果您的帐户有两步验证,您需要设置应用专用密码,然后在您的代码中使用该密码而不是主帐户密码。

我刚刚测试并验证了这适用于我的两步帐户。该死,这是我从 LINQPad 复制出来的整个方法,以防有帮助(当然删除了细节)。

var fromAddress = new MailAddress("myaccount@gmail.com", "My Name");
var toAddress = new MailAddress("test.address@email.com", "Mr Test");
const string fromPassword = "tbhagpfpcxwhkczd";
const string subject = "test";
const string body = "HEY, LISTEN!";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
    Timeout = 20000
};

using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

编辑:

使用附件:

using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    Attachment attachment = new Attachment(filePath);
    message.Attachments.Add(attachment);

    smtp.Send(message);
}

根据我使用 C# SMTP 客户端的经验,代码中有一定的步骤要遵循(请参见下面的代码片段)

smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Credentials = new NetworkCredential("account@gmail.com", "secretPassword");
smtpClient.Send(mail);