邮件 - smtp例外

时间:2013-12-04 09:02:49

标签: c# .net smtp

当我用C#编写邮件服务时,邮件发送成功。但接收者无法接收邮件。我读了它的日志:

Exception :System.Net.Mail.SmtpException: Send mail failed. ---> System.FormatException: An invalid character was found in header value
   at System.Net.Mime.HeaderCollection.Set(String name, String value)
   at System.Net.Mail.Message.PrepareHeaders(Boolean sendEnvelope)
   at System.Net.Mail.Message.BeginSend(BaseWriter writer, Boolean sendEnvelope, AsyncCallback callback, Object state)
   at System.Net.Mail.MailMessage.BeginSend(BaseWriter writer, Boolean sendEnvelope, AsyncCallback callback, Object state)
   at System.Net.Mail.SmtpClient.SendMailCallback(IAsyncResult result)

如何解决这个问题?

这是我的代码:

public static bool Send(MailAddress Messagefrom, string MessageTo, string MessageSubject, string MessageBody)
        {
            MailMessage message = new MailMessage();
            message.From = Messagefrom;
            message.To.Add(MessageTo);
            message.Subject = MessageSubject;
            message.Body = MessageBody;
            message.IsBodyHtml = true;
            message.Priority = MailPriority.High;            
            MailHelper mh = new MailHelper();
            SmtpClient sc = mh.setSmtpClient("smtp.163.com", 25);            

            sc.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);  
            try
            {
                sc.SendAsync(message, message);                
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

消息体是:

[SysAdmin 发送给您的,〈建模流程〉 建物理表 业务|EcaClient:Cmd=OpenTask&TaskGuid={3866BB12-0DFB-4713-9C89-043C228FDA3A}&UserID=271&Sender=1]

这是编码问题吗?我测试一下:当身体非常简单时,它正常工作。但是当这样变得复杂时,它就无法接收。如何解决?

2 个答案:

答案 0 :(得分:2)

尝试将BodyEncoding设置为utf8(默认为us-ascii):

message.BodyEncoding =  System.Text.Encoding.UTF8;

答案 1 :(得分:0)

试试这个

 System.Net.Mail.MailMessage mail_msg = new System.Net.Mail.MailMessage();
            System.Net.Mail.MailAddress fromAdd = new System.Net.Mail.MailAddress("from");
            mail_msg.From = fromAdd;
            mail_msg.Subject = "subject";
            mail_msg.IsBodyHtml = true;
            mail_msg.Body = "message";
            mail_msg.Bcc.Add("bcc"); //optional
            mail_msg.CC.Add("cc"); //optional
            SmtpClient smtp = new SmtpClient();
            smtp.UseDefaultCredentials = false;
 System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
            NetworkCred.UserName ="email";
            NetworkCred.Password = "password";
            smtp.Credentials = NetworkCred;
            smtp.Host = "host";  // EX. smtp.gmail.com
            smtp.Port = 25; 
            smtp.Timeout = 500000;
            smtp.EnableSsl = true;
            smtp.Send(mail_msg);