How to set username and password for SmtpClient object in .NET?

前端 未结 4 1876
抹茶落季
抹茶落季 2020-12-01 00:07

I see different versions of the constructor, one uses info from web.config, one specifies the host, and one the host and port. But how do I set the username and password to

相关标签:
4条回答
  • 2020-12-01 00:19

    Since not all of my clients use authenticated SMTP accounts, I resorted to using the SMTP account only if app key values are supplied in web.config file.

    Here is the VB code:

    sSMTPUser = ConfigurationManager.AppSettings("SMTPUser")
    sSMTPPassword = ConfigurationManager.AppSettings("SMTPPassword")
    
    If sSMTPUser.Trim.Length > 0 AndAlso sSMTPPassword.Trim.Length > 0 Then
        NetClient.Credentials = New System.Net.NetworkCredential(sSMTPUser, sSMTPPassword)
    
        sUsingCredentialMesg = "(Using Authenticated Account) " 'used for logging purposes
    End If
    
    NetClient.Send(Message)
    
    0 讨论(0)
  • 2020-12-01 00:21

    The SmtpClient can be used by code:

    SmtpClient mailer = new SmtpClient();
    mailer.Host = "mail.youroutgoingsmtpserver.com";
    mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
    
    0 讨论(0)
  • 2020-12-01 00:21

    Use NetworkCredential

    Yep, just add these two lines to your code.

    var credentials = new System.Net.NetworkCredential("username", "password");
    
    client.Credentials = credentials;
    
    0 讨论(0)
  • 2020-12-01 00:23
    SmtpClient MyMail = new SmtpClient();
    MailMessage MyMsg = new MailMessage();
    MyMail.Host = "mail.eraygan.com";
    MyMsg.Priority = MailPriority.High;
    MyMsg.To.Add(new MailAddress(Mail));
    MyMsg.Subject = Subject;
    MyMsg.SubjectEncoding = Encoding.UTF8;
    MyMsg.IsBodyHtml = true;
    MyMsg.From = new MailAddress("username", "displayname");
    MyMsg.BodyEncoding = Encoding.UTF8;
    MyMsg.Body = Body;
    MyMail.UseDefaultCredentials = false;
    NetworkCredential MyCredentials = new NetworkCredential("username", "password");
    MyMail.Credentials = MyCredentials;
    MyMail.Send(MyMsg);
    
    0 讨论(0)
提交回复
热议问题