如何通过Gmail发送带有C#的电子邮件

时间:2015-04-06 03:50:36

标签: c# smtp gmail smtpclient

尝试通过我的网络服务发送电子邮件时出错。我已尝试启用访问不太安全的应用程序,禁用两步验证并通过Web浏览器登录帐户。 SO的解决方案都没有对我有用。我还在:

  

错误:System.Net.Mail.SmtpException:SMTP服务器需要a   安全连接或客户端未经过身份验证。服务器   响应是:5.5.1需要验证。

我该怎么做才能解决这个问题?

namespace EmailService
{
    public class Service1 : IService1
    {    
        public string SendEmail(string inputEmail, string subject, string body)
        {
            string returnString = "";
            try
            {
                MailMessage email = new MailMessage();
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";

                // set up the Gmail server
                smtp.EnableSsl = true;
                smtp.Port = 587;
                smtp.Credentials = new System.Net.NetworkCredential("myemail@gmail.com", "mypassword");
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.UseDefaultCredentials = false;

                // draft the email
                MailAddress fromAddress = new MailAddress("cse445emailservice@gmail.com");
                email.From = fromAddress;
                email.To.Add(inputEmail);
                email.Subject = body;
                email.Body = body;

                smtp.Send(email);

                returnString = "Success! Please check your e-mail.";
            }
            catch(Exception ex)
            {
                returnString = "Error: " + ex.ToString();
            }
            return returnString;
        }
    }
}

1 个答案:

答案 0 :(得分:33)

只需转到此处:Less secure apps,使用您的电子邮件和密码登录,用于在c#代码中发送邮件,然后选择Turn On

另请点击此链接,然后点击继续 Allow access to your Google account

我也稍微编辑一下:

public string sendit(string ReciverMail)
{
    MailMessage msg = new MailMessage();

    msg.From = new MailAddress("YourMail@gmail.com");
    msg.To.Add(ReciverMail);
    msg.Subject = "Hello world! " + DateTime.Now.ToString();
    msg.Body = "hi to you ... :)";
    SmtpClient client = new SmtpClient();
    client.UseDefaultCredentials = true;
    client.Host = "smtp.gmail.com";
    client.Port = 587;
    client.EnableSsl = true;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.Credentials = new NetworkCredential("YourMail@gmail.com", "YourPassword");
    client.Timeout = 20000;
    try
    {
       client.Send(msg);
        return "Mail has been successfully sent!";
    }
    catch (Exception ex)
    {
        return "Fail Has error" + ex.Message;
    }
    finally
    {
       msg.Dispose();
    }
}

如果上述代码无效,请尝试按以下代码进行更改:

    SmtpClient client = new SmtpClient();
    client.Host = "smtp.gmail.com";
    client.Port = 587;
    client.EnableSsl = true;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.Credentials = new NetworkCredential("YourMail@gmail.com", "YourPassword");