180

コンストラクターのさまざまなバージョンが表示されます。1 つは web.config の情報を使用し、1 つはホストを指定し、もう 1 つはホストとポートを指定します。しかし、ユーザー名とパスワードを web.config とは異なるものに設定するにはどうすればよいでしょうか? 内部 smtp が一部の高セキュリティ クライアントによってブロックされているという問題があり、それらの smtp サーバーを使用したいのですが、web.config の代わりにコードからこれを行う方法はありますか?

この場合、たとえばデータベースから何も利用できない場合、web.config資格情報をどのように使用しますか?

public static void CreateTestMessage1(string server, int port)
{
    string to = "jane@contoso.com";
    string from = "ben@contoso.com";
    string subject = "Using the new SMTP client.";
    string body = @"Using this new feature, you can send an e-mail message from an application very easily.";
    MailMessage message = new MailMessage(from, to, subject, body);
    SmtpClient client = new SmtpClient(server, port);
    // Credentials are necessary if the server requires the client 
    // to authenticate before it will send e-mail on the client's behalf.
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    try {
        client.Send(message);
    }
    catch (Exception ex) {
        Console.WriteLine("Exception caught in CreateTestMessage1(): {0}", 
                    ex.ToString());
    }              
}
4

5 に答える 5

333

SmtpClient はコードで使用できます。

SmtpClient mailer = new SmtpClient();
mailer.Host = "mail.youroutgoingsmtpserver.com";
mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
于 2010-05-04T16:10:11.513 に答える
33

使用するNetworkCredential

はい、この 2 行をコードに追加するだけです。

var credentials = new System.Net.NetworkCredential("username", "password");

client.Credentials = credentials;
于 2010-05-04T16:09:41.097 に答える
-3

すべてのクライアントが認証済みの SMTP アカウントを使用しているわけではないため、web.config ファイルでアプリ キーの値が指定されている場合にのみ、SMTP アカウントを使用することにしました。

VBコードは次のとおりです。

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)
于 2016-12-14T05:20:34.083 に答える