SmtpClient

in 未分类

说实话,这篇日志写上来自己都觉得惭愧!-_____-
.Net 2.0中SmtpClient类是专门用来发送电子邮件的。
刚好,今天用上了。
用SmtpClient类发送邮件异常简单,
但今天却让我大伤脑筋
先看下面的代码:

try
            {
                SmtpClient sc = new SmtpClient(_mailServer, _serverPort);
                sc.Credentials = new System.Net.NetworkCredential(_mailUsername, _mailPassword);
                sc.UseDefaultCredentials = true;
                sc.EnableSsl = EnableSSL;
                sc.Send(mail);
                return true;
            }
假定_mailServer、_serverPort及各参数都正确,这个try语句块能顺利通过吗?
感觉上应该可以完全通过,但事实上,抛出了异常。
那为什么会失败?
问题就出现在
sc.UseDefaultCredentials = true;

注意:此属性在 .NET Framework 2.0 版中是新增的。
获取或设置 Boolean 值,该值控制 DefaultCredentials 是否随请求一起发送。

将sc.UseDefaultCredentials = true;放到sc.Credentials这句之前就OK了。
即:
try
            {
                SmtpClient sc = new SmtpClient(_mailServer, _serverPort);
                sc.UseDefaultCredentials = true;
                sc.Credentials = new System.Net.NetworkCredential(_mailUsername, _mailPassword);

                sc.EnableSsl = EnableSSL;
                sc.Send(mail);
                return true;
            }
这样就行了

1 Comment

One Comment

  1. 我是个初学者,想弄一个邮件发送的系统。你能给我这部分的全部代码吗?
    panqintao@sina.com

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>