System.Net.Mail.SMTPException:发送邮件失败

时间:2012-05-16 19:30:31

标签: .net email smtp gmail

我已多次尝试使用以下代码发送附件。我使用了端口25,465,467和587都导致了同样的错误。我已经通过其他帖子搜索同样的问题或接近同样的问题,并尝试了许多修复,但没有一个适合我。救命!

try
{
    var smtp = new SmtpClient
    {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new System.Net.NetworkCredential("thisisjustatestokay1@gmail.com", "xxxxxxxxxxxx")
    };
    using (var message = new MailMessage("thisisjustatestokay1@gmail.com", "thisisjustatestokay1@gmail.com")
        {
            Subject = "Boom Baby!",
            Body = "The stuff!"
        })
    {
        smtp.Send(message);
    }
}
catch (Exception e)
{
    MessageBox.Show(e.Message);
}

2 个答案:

答案 0 :(得分:0)

代码看起来不错,但我修改了它,如下所示,它完美无缺。

protected void Btn_SendMail_Click(object sender, EventArgs e){

  var smtp = new SmtpClient {
    Host = "smtp.gmail.com",
    Port = 587, 
    EnableSsl = true, 
    DeliveryMethod = SmtpDeliveryMethod.Network, 
    UseDefaultCredentials = false, 
    Credentials = new System.Net.NetworkCredential("someone@gmail.com","**********")
  };

  MailMessage mailObj = new MailMessage("someone@gmail.com", txtTo.Text, txtSubject.Text, txtBody.Text);

  smtp.Send(mailObj);

}

答案 1 :(得分:-1)

<强> I have tried repeatedly to send an attachment using the following code

您的代码缺失,无法在电子邮件中添加附件。

System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("path of the file to be attached");
mail.Attachments.Add(attachment);