smtp异常“发送邮件失败”

时间:2015-08-26 16:04:42

标签: c# email console-application

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

    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帐户设置吗?

2 个答案:

答案 0 :(得分:8)

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

  

SMTP服务器需要安全连接,或者客户端未经过身份验证。服务器响应为:5.5.1需要身份验证。

更改此段代码并添加一行。它必须在证书之前。

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://github.com/nervgh/angular-file-upload

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

我刚刚在我的两步帐户上测试并验证了这项工作。地狱,这是我的整个方法,直接从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);
}

答案 1 :(得分:0)

以我使用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);