using System.Net.Mail;试了很多SMTP发送邮件的代码,结果相同。代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;namespace 测试
{              //smtp类 
    class Class1
    {
        static bool mailSent = false;
        public static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation. 
            String token = (string)e.UserState;            if (e.Cancelled)
            {
                Console.WriteLine("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
            }
            else
            {
                Console.WriteLine("Message sent.");
            }
            mailSent = true;
        }
        public static void Main(string[] args)
        {
            string svr = "mail.lierda.com";
            // Command line argument must the the SMTP host. 
            SmtpClient client = new SmtpClient(svr, 25);            // Specify the e-mail sender. 
            // Create a mailing address that includes a UTF8 character 
            // in the display name. 
            MailAddress from = new MailAddress("[email protected]");
               // "yuxiaozhong" + (char)0xD8 + "4821698",System.Text.Encoding.UTF8);
            // Set destinations for the e-mail message. 
            MailAddress to = new MailAddress("[email protected]");
            // Specify the message content. 
            MailMessage message = new MailMessage(from, to);
            message.Body = "This is a test e-mail message sent by an application. ";
            // Include some non-ASCII characters in body and subject. 
            string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
            message.Body += Environment.NewLine + someArrows;
            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.Subject = "test message 1" + someArrows;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            // Set the method that is called back when the send operation ends. 
            client.SendCompleted += new  SendCompletedEventHandler(SendCompletedCallback);
            // The userState can be any object that allows your callback  
            // method to identify this send operation. 
            // For this example, the userToken is a string constant. 
            string userState = "test message1";
            client.Credentials = new System.Net.NetworkCredential(from.Address, "11181118", "lierda.com");//
            client.SendAsync(message, userState);
            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");            string answer = Console.ReadLine();            // If the user canceled the send, and mail hasn't been sent yet, 
            // then cancel the pending operation. 
            //client.SendAsyncCancel(); 
            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }
            // Clean up. 
            message.Dispose();
            Console.WriteLine("Goodbye.");
        }
    }
}

解决方案 »

  1.   

    你现在什么问题?
    最近刚刚为公司开发了一个邮件收发系统
    用的system.net.mail做的.
      

  2.   

    发送邮件Send方法调用后产生异常:
    "在邮件标头中找到无效的字符"。1、同样的代码曾经是正确的。
    2、用VC编写的SMTP程序发送没问题,FOXMAIL发送也没问题,说明API层没问题(想想应该是FRAMWORK有问题,但不知怎么解决)。
    3、相同的问题搜了一下挺多,但没有合适的解决方法。
      

  3.   

    message.SubjectEncoding = System.Text.Encoding.GetEncoding("936");
    试试看这个编码格式
      

  4.   

    下面的代码也发不出去,问题在哪里啊,真的要疯了:
    protected void Button5_Click(object sender, EventArgs e)
        {
            string from = "[email protected]";// "[email protected]";
            string svr = "smtp.gmail.com";//mail.lierda.com
            int port = 587;        MailMessage myEmail = new MailMessage();
            myEmail.From = new MailAddress(from, "zxyu");
            myEmail.To.Add(new MailAddress("[email protected]"));
            myEmail.Subject = "test"; //edtSubject.Text.Trim();
            //myEmail.SubjectEncoding = System.Text.Encoding.GetEncoding("936");         myEmail.Body = "test"; //edtContent.Text.Trim();
            myEmail.IsBodyHtml = true;
            myEmail.Priority = MailPriority.High;
            //构造添加附件
            //string attachFile = @"c:\Lsd20071113.log";
            //Attachment fujian = new Attachment(attachFile);
            //myEmail.Attachments.Add(fujian);
     
            //发送电子邮件
            SmtpClient sc = new SmtpClient(svr, port);
            //sc.UseDefaultCredentials = false;        sc.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
            //sc.Host = strHost; ;//指定SMTP服务器
            sc.Credentials = new System.Net.NetworkCredential(from, "xxxxxx");//
            sc.EnableSsl = true;//
            //try
            {
                sc.Send(myEmail);
                Response.Redirect(Request.Url.ToString());
            }
            //catch(Exception ex)
            //{
             //   Response.Redirect("MsgOk.aspx?msg=" + ex.Message);
           // }
            
        }
      

  5.   

    异常详细信息: System.FormatException: 在邮件标头中找到无效的字符。源错误: 
    行 132:        //try
    行 133:        {
    行 134:            sc.Send(myEmail);
    行 135:            Response.Redirect(Request.Url.ToString());
    行 136:        }
     源文件: k:\ZxyMembership\Default.aspx.cs    行: 134 堆栈跟踪: 
    [FormatException: 在邮件标头中找到无效的字符。]
       System.Net.BufferBuilder.Append(String value, Int32 offset, Int32 count) +144
       System.Net.BufferBuilder.Append(String value) +57
       System.Net.Mail.EHelloCommand.PrepareCommand(SmtpConnection conn, String domain) +143
       System.Net.Mail.EHelloCommand.Send(SmtpConnection conn, String domain) +30
       System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) +1166
       System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) +287
       System.Net.Mail.SmtpClient.GetConnection() +56
       System.Net.Mail.SmtpClient.Send(MailMessage message) +1671[SmtpException: 发送邮件失败。]
       System.Net.Mail.SmtpClient.Send(MailMessage message) +2236
       _Default.Button5_Click(Object sender, EventArgs e) in k:\ZxyMembership\Default.aspx.cs:134
       System.Web.UI.WebControls.Button.OnClick(EventArgs e) +96
       System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +116
       System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +31
       System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +32
       System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +72
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3839 
      

  6.   

    应该是Framework的问题吧,你用低版本试一试
      

  7.   

    我也与到了相同的问题,代码以前是好使的,但现在也报错
    错误内容是"在头值中找到无效的字符"楼上有一个兄弟说FRAMEWORK版本的问题,我也怀疑,因为我刚刚打了.net framework 2.0的补丁1是不是这个东西影响的还真不知道.
      

  8.   

    我的问题解决了,楼主也试试,
    主要是这句话的问题
    MailAddress from = new MailAddress(mstrFrom , "应用监控");
    应该改成
    MailAddress from = new MailAddress(mstrFrom , "应用监控",Encoding.BigEndianUnicode);
    编码我试了很多种只有这个编码才不报错,才能识别中文其它的编码都可以识别英文.
      

  9.   

    Encoding.BigEndianUnicode编码也是失败。
    同样的代码在其他机器上运行成功。
      

  10.   

    16楼的wtk13:
    vc的SMTP程序和FOXMAIL可以正常发送,可以确定系统API没问题。
    如果是编码的问题或者是Framework的问题,那么学习。NET的必要性真的要打折扣了;
    对于这样的问题,MS有比较权威的解释吗,哪怕说你的操作系统是盗版的,所以。
      

  11.   

    我是用jmail实现的。我对jmail偏爱。呵呵,用微软的类也可以实现。可能会稍微麻烦点。利用asp.net+Jmail发送Email
      

  12.   

    非常感谢小灰(www.svnhost.cn)!可爱的小灰 小美女 已经若干次无私地帮助我了,这次全分献上。另外虽没给分,但还是感谢楼上各位!
      

  13.   

    呵,我和楼主遇到的问题一样,原因是如此
    http://makoma.blog.hexun.com/16453328_d.html
    M$ 工程师为了避开重复作编码的动作, 每次呼叫 ToEncodedString( ) 及 ToString( ) 时都会去看看 fullAddress 这个 private field 是否有值? 有的话代表之前已经作过编码了, 就直接捡现成. 问题出在第一次呼叫时, 编码的动作在 ToString( ) 及 ToEncodedString( ) 各写了一次 (果然没有做好 refactoring ... 哈哈), 结果 ToString( ) 的这份 code implementation 是错的, 跟本没编码 ...
    在我的程序中原来是这样的:
     this.Body = mailbody
     this.Subject = rule.RuleName
    加入.toString()后,问题解决!
     this.Body = mailbody.ToString();
     this.Subject = rule.RuleName.ToString();
    主要问题是this.Subject出了问题
      

  14.   

    还有如 this.Subject中有特殊符号也会报这样的异常

    18:02
    []
    等等
      

  15.   

    bug 来的 http://support.microsoft.com/kb/947323/zh-cn
      

  16.   


    system.net.mail 会出现:
     在邮件标头中找到无效的字符。