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.");
}
}
}
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.");
}
}
}
最近刚刚为公司开发了一个邮件收发系统
用的system.net.mail做的.
"在邮件标头中找到无效的字符"。1、同样的代码曾经是正确的。
2、用VC编写的SMTP程序发送没问题,FOXMAIL发送也没问题,说明API层没问题(想想应该是FRAMWORK有问题,但不知怎么解决)。
3、相同的问题搜了一下挺多,但没有合适的解决方法。
试试看这个编码格式
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);
// }
}
行 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
错误内容是"在头值中找到无效的字符"楼上有一个兄弟说FRAMEWORK版本的问题,我也怀疑,因为我刚刚打了.net framework 2.0的补丁1是不是这个东西影响的还真不知道.
主要是这句话的问题
MailAddress from = new MailAddress(mstrFrom , "应用监控");
应该改成
MailAddress from = new MailAddress(mstrFrom , "应用监控",Encoding.BigEndianUnicode);
编码我试了很多种只有这个编码才不报错,才能识别中文其它的编码都可以识别英文.
同样的代码在其他机器上运行成功。
vc的SMTP程序和FOXMAIL可以正常发送,可以确定系统API没问题。
如果是编码的问题或者是Framework的问题,那么学习。NET的必要性真的要打折扣了;
对于这样的问题,MS有比较权威的解释吗,哪怕说你的操作系统是盗版的,所以。
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出了问题
如
18:02
[]
等等
system.net.mail 会出现:
在邮件标头中找到无效的字符。