SmtpClient with Gmail

后端 未结 6 720
忘了有多久
忘了有多久 2020-11-29 03:47

I\'m developing a mail client for a school project. I have managed to send e-mails using the SmtpClient in C#. This works perfectly with any server but it doesn

6条回答
  •  眼角桃花
    2020-11-29 04:31

    Gmail's SMTP server requires you to authenticate your request with a valid gmail email/password combination. You do need SSL enabled as well. Without actually being able to see a dump of all your variables being passed in the best guess I can make is that your Credentials are invalid, make sure you're using a valid GMAIL email/password combination.

    You might want to read here for a working example.

    EDIT: Okay here's something I wrote and tested just then and it worked fine for me:

    public static bool SendGmail(string subject, string content, string[] recipients, string from) {
        if (recipients == null || recipients.Length == 0)
            throw new ArgumentException("recipients");
    
        var gmailClient = new System.Net.Mail.SmtpClient {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            UseDefaultCredentials = false,
            Credentials = new System.Net.NetworkCredential("******", "*****")
        };
    
        using (var msg = new System.Net.Mail.MailMessage(from, recipients[0], subject, content)) {
            for (int i = 1; i < recipients.Length; i++)
                msg.To.Add(recipients[i]);
    
            try {
                gmailClient.Send(msg);
                return true;
            }
            catch (Exception) {
                // TODO: Handle the exception
                return false;
            }
        }
    }
    

    If you need any more info there's a similar SO article here

提交回复
热议问题