最近做一个小东西,用到邮件发送, 就用了开源代码 OpenSmtp来发送邮件
发现发送附件文件名字为中文时候,文件名会变成=B1=D3=DA18:00=BD=F8=C8=EB=BF=BC=B3=A1.txt这样的文件名,
经过仔细检查代码,发现往邮件添加附件的时候,
调用ConvertToQP()函数对附件进行编码,
该方法作用是主要是对内容进行Quoted-Printable编码
下面这个函数,通过函数名,我们知道,它返回邮件内容部分,包括经过编码的附件内容
private String GetMessageBody()

{
StringBuilder sb=new StringBuilder();
if (attachments.Count>0)

{
sb.Append("Content-Type: multipart/mixed;");
sb.Append("boundary=\"" + mixedBoundary + "\"");
sb.Append("\r\n\r\nThis is a multi-part message in MIME format.");
sb.Append("\r\n\r\n--" + mixedBoundary + "\r\n");
}
sb.Append(GetInnerMessageBody());
if (attachments.Count>0)

{
foreach (Attachment attachment in attachments)

{
sb.Append("\r\n\r\n--" + mixedBoundary + "\r\n");
sb.Append(attachment.ToMime());
}
sb.Append("\r\n\r\n--" + mixedBoundary + "--\r\n");
}
return sb.ToString();
}
附件的信息写在 sb.Append(attachment.ToMime());这句里面,我们再来看看 attachment.ToMime();绿色注释部分是原代码,经过修改,该方法如下:
filename,name不经过QP编码,这样就能显示正常的附件名字了
public String ToMime()

{
StringBuilder sb=new StringBuilder();
if (ContentId!=null)

{
sb.Append("Content-ID: <" + ContentId + ">\r\n");
}
sb.Append("Content-Type: " + mimeType + ";\r\n");
sb.Append(" name=\"" + name + "\"\r\n");
//sb.Append(" name=\"" + MailEncoder.ConvertToQP(name,null;) + "\"\r\n");
sb.Append("Content-Transfer-Encoding: " + encoding + "\r\n");
sb.Append("Content-Disposition: attachment;\r\n");
sb.Append(" filename=\"" + name + "\"\r\n\r\n");
//sb.Append(" filename=\"" + MailEncoder.ConvertToQP(name,null) + "\"\r\n\r\n");
FileStream fin = new FileStream(encodedFilePath, FileMode.Open, FileAccess.Read);
byte[] bin;
while (fin.Position != fin.Length)

{
bin = new byte[76];
int len = fin.Read(bin, 0, 76);
sb.Append(System.Text.Encoding.UTF8.GetString(bin , 0, len)+"\r\n");
}
fin.Close();
return sb.ToString();
}
不过这样做是不是有什么问题呢?还请各位用过OpenSmtp的大侠指教