我用网上的C#实现的SMTP发送邮件代码,在有WORD、PDF、EXCEL等附件时,有的邮件客户端会打不开。
1、用网页登录邮箱收件箱直接打开会是乱码,保存到本地又可以打开
2、用FOXMAIL收取时可在客户端直接打开,保存本地也可以打开
3、用公司自己的OA客户端又打不开,并且保存到本地也打不开
相关附件的实现代码如下(环境还是VS2003):完整的代码请参考:http://wenku.baidu.com/view/c41c1b4f852458fb770b56cf.html
if(mailMessage.Attachments.Count!=0) //mailMessage.Attachments是用来存放附件的数组
{
SendBufferstr += "--=====001_Dragon303406132050_====="+CRLF;

SendBufferstr+="Content-Type: text/plain;" + CRLF;
SendBufferstr+=((mailMessage.Charset=="")?(" charset=\"iso-8859-1\""):(" charset=\"" +
mailMessage.Charset.ToLower() + "\"")) + CRLF;
SendBufferstr+="Content-Transfer-Encoding: base64" + CRLF + CRLF;
SendBufferstr+= Base64Encode(mailMessage.Body) + CRLF;for(int i=0;i<mailMessage.Attachments.Count;i++)
{
string filepath = (string)mailMessage.Attachments[i];
SendBufferstr += "--====="+ 
(Html?"001_Dragon520636771063_":"001_Dragon303406132050_") +"====="+CRLF;
//SendBufferstr += "Content-Type: application/octet-stream"+CRLF;
SendBufferstr += "Content-Type: text/plain;"+CRLF;
SendBufferstr += " name=\"=?"+mailMessage.Charset.ToUpper()+"?B?"+
Base64Encode(filepath.Substring(filepath.LastIndexOf("\\")+1))+"?=\""+CRLF;
SendBufferstr += "Content-Transfer-Encoding: base64"+CRLF;
SendBufferstr += "Content-Disposition: attachment;"+CRLF;
SendBufferstr += " filename=\"=?"+mailMessage.Charset.ToUpper()+"?B?"+
Base64Encode(filepath.Substring(filepath.LastIndexOf("\\")+1))+"?=\""+CRLF+CRLF;
SendBufferstr += GetStream(filepath)+CRLF+CRLF;
}
SendBufferstr += "--====="+(Html?"001_Dragon520636771063_":"001_Dragon303406132050_")+"=====--"+CRLF+CRLF;相关两个函数的代码如下:
/// <summary>
/// 将字符串编码为Base64字符串
/// </summary>
/// <param name="str">要编码的字符串</param>
public string Base64Encode(string str)
{
byte[] barray;
barray=Encoding.Default.GetBytes(str);
return Convert.ToBase64String(barray);
}
/// <summary>
/// 得到上传附件的文件流
/// </summary>
/// <param name="FilePath">附件的绝对路径</param>
public string GetStream(string FilePath)
{
//建立文件流对象
System.IO.FileStream FileStr=new System.IO.FileStream(FilePath,System.IO.FileMode.Open);
byte[] by=new byte[System.Convert.ToInt32(FileStr.Length)];
FileStr.Read(by,0,by.Length);
FileStr.Close();
return(System.Convert.ToBase64String(by));
}

解决方案 »

  1.   

    试下把Base64Encode改成下面这样: public string Base64Encode(string str, string encoding)
    {
    byte[] barray;
    barray = Encoding.GetEncoding("encoding").GetBytes(str);
    return Convert.ToBase64String(barray);
    }然后调用时:
       string encoding = mailMessage.Charset == "" ? "utf-8" : mailMessage.Charset;
       SendBufferstr+= Base64Encode(mailMessage.Body, encoding) + CRLF;上面的缺省charset最好也改成utf-8,不要用iso-8859-1
      

  2.   

    不要用Encoding.Default,改用Encoding.UTF8