send email in c#

前端 未结 6 1532
猫巷女王i
猫巷女王i 2021-01-28 04:56

i\'ve tried to send email using this code..but an error occurred in smtp.Send(mail); messaging \"Failure sending mail\"

  MailMessage mail = ne         


        
6条回答
  •  醉话见心
    2021-01-28 05:27

    Here's a basic GMAIL smtp email implementation I wrote a while ago:

    public static bool SendGmail(string subject, string content, string[] recipients, string from)
    {
        bool success = recipients != null && recipients.Length > 0;
    
        if (success)
        {
            SmtpClient gmailClient = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                UseDefaultCredentials = false,
                Credentials = new System.Net.NetworkCredential("******", "*****") //you need to add some valid gmail account credentials to authenticate with gmails SMTP server.
            };
    
    
            using (MailMessage gMessage = new MailMessage(from, recipients[0], subject, content))
            {
                for (int i = 1; i < recipients.Length; i++)
                    gMessage.To.Add(recipients[i]);
    
                try
                {
                    gmailClient.Send(gMessage);
                    success = true;
                }
                catch (Exception) { success = false; }
            }
        }
        return success;
    }
    

    It should work fine for you, but you'll need to add a valid gmail acocunt where I've marked in the code.

提交回复
热议问题