Sending mail using Gmail

僤鯓⒐⒋嵵緔 提交于 2019-12-08 12:43:26

问题


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;
    }
}

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.


回答1:


try

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

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.




回答2:


Please try with Port 25. It's working for me. Also remove setting of UseDefaultCredentials.

Update : Port 587 also working for me. So I think UseDefaultCredentials is only problem in your code. it should be set to false.

public static void SendMail(string ToMail, string FromMail, string Cc, string Body, string Subject)
{
    SmtpClient smtp = new SmtpClient("smtp.gmail.com", 25);
    MailMessage mailmsg = new MailMessage();

    smtp.EnableSsl = true;
    smtp.Credentials = new NetworkCredential("email","password");

    mailmsg.From = new MailAddress(FromMail);
    mailmsg.To.Add(ToMail);

    if (Cc != "")
    {
       mailmsg.CC.Add(Cc);
    }
    mailmsg.Body = Body;
    mailmsg.Subject = Subject;
    mailmsg.IsBodyHtml = true;

    mailmsg.Priority = MailPriority.High;

    try
    {
       smtp.Timeout = 500000;
       smtp.Send(mailmsg);
       mailmsg.Dispose();
    }
    catch (Exception ex)
    {
       throw ex;
    }
}


来源:https://stackoverflow.com/questions/7550863/sending-mail-using-gmail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!