使用Gmail发送邮件 [英] Sending mail using Gmail

查看:190
本文介绍了使用Gmail发送邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于使用Gmail发送邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆