Confused with the SmtpClient.UseDefaultCredentials Property

前端 未结 4 1531
后悔当初
后悔当初 2020-12-16 14:30

In my MVC4 application, I\'m using the SmtpClient to send out email via Gmail\'s smtp.gmail.com SMTP server.

I\'ve configured my Web.Config

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 15:20

    This is how we can create SMTP Client with or without NetworkCredentials. I am using this code to send emails. We should use client.UseDefaultCredentials only when we are not passing credentials and going by default.

            private SmtpClient InitializeSMTPClient()
            {
                var client = new SmtpClient(_smtpServer, _smtpPort);
    
                client.UseDefaultCredentials = _useSMTPDefaultCredentials;
    
                if (_useSMTPDefaultCredentials)
                    return client;
    
                var credentials = new NetworkCredential(_smtpUsername, _smtpPassword);
                client.Credentials = credentials;
    
                return client;
            }
    
    
    
            SMTPEmailResult SendSMTPEmail(List to_email, List ccEmails, string subject, string message)
            {
                try
                {
                    using (var client = InitializeSMTPClient())
                    {
                        var mail_message = GetMailMessage(to_email, ccEmails, subject, message);
                        log.Debug("Sending SMTP email.");
                        client.Send(mail_message);
                        log.Debug("SMTP email sent successfully.");
                        return SMTPEmailResult.SendSuccess;
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message, ex);
                    return SMTPEmailResult.SendFailed;
                }
            }
    

提交回复
热议问题