使用Gmail发送邮件发送邮件、Gmail

2023-09-04 06:17:05 作者:羁拥

public static bool SendMail(string toList, string from, string ccList, string subject, string body)
{
    MailMessage message = new MailMessage();
    SmtpClient smtpClient = new SmtpClient();

    try
    {
        MailAddress fromAddress = new MailAddress(from);
        message.From = fromAddress;
        message.To.Add(toList);
        if (ccList != null && ccList != string.Empty)
            message.CC.Add(ccList);
        message.Subject = subject;
        message.IsBodyHtml = true;
        message.Body = body;

        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpClient.EnableSsl = true;
        smtpClient.Timeout = 30000;
        smtpClient.Host = "smtp.gmail.com";   // We use gmail as our smtp client
        smtpClient.Port = 587;
        smtpClient.UseDefaultCredentials = true;
        smtpClient.Credentials = new System.Net.NetworkCredential("myemail@gmail.com", "mypassword");


        smtpClient.Send(message);
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

在code似乎确定,但仍然没有工作,我无法弄清楚,为什么? 任何其他方式使用Gmail的SMTP发送邮件。

The code seems ok, but still not working, I am not able to figure out why? any other way to use gmail's smtp to send mail.

推荐答案

尝试

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");

如果在 UseDefaultCredentials 属性设置为,然后在设定的值证书属性连接到服务器时,将使用的凭据。在这里,您设置 UseDefaultCredentials 然后它会忽略你定的凭据。

If the UseDefaultCredentials property is set to false, then the value set in the Credentials property will be used for the credentials when connecting to the server. Here you set UseDefaultCredentials as true then it will neglect credentials you given.