asp.net 发邮件乱码,该怎么解决
发布网友
发布时间:2022-04-24 06:28
我来回答
共1个回答
热心网友
时间:2022-04-27 10:08
发送邮件的代码如下:using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using jmail;
using System.IO;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
public partial class getemail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void sendEmail_Click(object sender, EventArgs e)
{
#region
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Credentials = new NetworkCredential("likeshan168@gmail.com", "likeshannihao168");
MailMessage mail = new MailMessage("likeshan168@gmail.com", emailRec.Text.Trim());
mail.Subject = subject.Text.Trim();
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = emailbody.Text.Trim();
mail.BodyEncoding = System.Text.Encoding.UTF8;
smtpClient.EnableSsl = true;
string attafile = fileUpload.PostedFile.FileName;
if (!string.IsNullOrEmpty(attafile))//这里是添加附件的作用
{
#region//方法一
//string filename = Path.GetFileName(attafile);
//fileUpload.PostedFile.SaveAs(Server.MapPath(filename));
//System.Net.Mail.Attachment atta = new System.Net.Mail.Attachment(Server.MapPath(filename));
//mail.Attachments.Add(atta);
#endregion
#region//方法二
//string filepath = Server.MapPath("~/UploadFile/Files");
//string extName = Path.GetExtension(attafile);
//if (!Directory.Exists(filepath))
//{
// Directory.CreateDirectory(filepath);
//}
//filepath = filepath + "\" + DateTime.Now.ToString("yyyyMMddhhMMssffff") + extName;
//fileUpload.PostedFile.SaveAs(filepath);
//System.Net.Mail.Attachment atta = null;
//if (extName == ".zip" || extName == ".rar")
//{
// atta = new System.Net.Mail.Attachment(filepath, MediaTypeNames.Application.Zip);
//}
//else
//{
// atta = new System.Net.Mail.Attachment(filepath, MediaTypeNames.Application.Octet);
//}
#endregion
#region//方法三
string filepath = Server.MapPath("~/UploadFile/Files");
string extName = Path.GetExtension(attafile);
if (!Directory.Exists(filepath))
{
Directory.CreateDirectory(filepath);
}
filepath = filepath + "\" + DateTime.Now.ToString("yyyyMMddhhMMssffff") + extName;
fileUpload.PostedFile.SaveAs(filepath);
System.Net.Mail.Attachment atta = null;
if (extName == ".zip" || extName == ".rar")
{
atta = new System.Net.Mail.Attachment(new FileStream(filepath, FileMode.Open, FileAccess.Read), attafile, MediaTypeNames.Application.Zip);
}
else
{
atta = new System.Net.Mail.Attachment(new FileStream(filepath, FileMode.Open, FileAccess.Read), attafile, MediaTypeNames.Application.Octet);
}
mail.Attachments.Add(atta);
#endregion
}
mail.Priority = MailPriority.Normal;
try
{
smtpClient.Send(mail);
ClientScript.RegisterClientScriptBlock(Page.GetType(), "tip1", "alert('发送成功!')", true);
}
catch (Exception ex)
{
ClientScript.RegisterClientScriptBlock(Page.GetType(), "tip2", "alert('" + ex.Message + "!')", true);
}
#endregion
}
}
接受邮件的代码
<%@ WebHandler Language="C#" Class="getEmail" %>
using System;
using System.Web;
using jmail;
using System.Text;
public class getEmail : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//context.Response.ContentType = "text/plain";
POP3Class popClient = new POP3Class();
try
{
popClient.Connect("likeshan168@163.com", "likeshannihao168", "pop.163.com", 110);
if (popClient != null)
{
if (popClient.Count > 0)//收件数目
{
StringBuilder sb = new StringBuilder();
Message msg = null;
for (int i = 0, len = popClient.Count; i < len; i++)
{
msg = popClient.Messages[i + 1];
string msgid = popClient.GetMessageUID(i + 1);//029DCA8D131AA92586C8FB6CB61B627B0E00000000000001(邮件在服务器中的唯一标识)
int c = popClient.GetLastUnreadMessage();
msg.ISOEncodeHeaders = false;
sb.Append("<p>时间:" + msg.Date.ToString() + "</p>");
sb.Append("<p>发件人:" + msg.From + "</p>");
string substr = msg.Headers.GetHeader("Subject");//只要有中文就会进行base64的编码,如果是英文的话,就不会进行base64的编码
if (substr.Contains("utf-8"))
{
substr = DecodeStr(substr.Split('?')[3], "utf-8");//=?utf-8?B?5pyJ5LiA5Liq5rWL6K+V?=
}
if (substr.Contains("gbk") || substr.Contains("GBK") || substr.Contains("GB2312"))
{
substr = DecodeStr(substr.Split('?')[3], "gbk");
}
sb.Append("<p>主题:" + substr + "</p>");
sb.Append("<p>内容:" + msg.Body + "</p>");
int attaCount = msg.Attachments.Count;
for (int j = 0; j < attaCount; j++)
{
sb.Append("<p>附件(" + (j + 1).ToString() + "):" + msg.Attachments[j].Name + "</p>");
}
}
context.Response.Write(sb.ToString());
}
}
}
catch (Exception ex)
{
context.Response.Write(ex.Message);
}
}
public bool IsReusable
{
get
{
return false;
}
}
public static string base64GbkDecode(string data)
{
string decode = "";
byte[] bytes = Convert.FromBase64String(data);//先经过base64解码,在经过gbk2312解码
try
{
decode = Encoding.GetEncoding("gb2312").GetString(bytes);
}
catch (Exception ex1)
{
return "Error in base64Encode" + ex1.Message;
}
return decode;
}
public static string base64Utf8Decode(string data)
{
string result = "";
try
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();//获取解码器
byte[] todecode_byte = Convert.FromBase64String(data);//先经过base64解码,在经过utf-8解码
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);//多少个字符
char[] decoded_char = new char[charCount];//字符字符数组
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);//解码到字符数组
result = new String(decoded_char);
}
catch (Exception e)
{
return "Error in base64Encode" + e.Message;
}
return result;
}
//base64解码
public static string DecodeStr(string allstr, string code)
{
//形如=?...?=是结束开始的标志
//=?utf-8?B?5rWL6K+V5o6l5pS25pys6YKu5Lu26L+Z5piv5Li76aKY?=
//=?gbk?B?suLK1L3TytXN4rK/08q8/tXiuPbKx9b3zOU=?=
//返回的字符串
string str = "";
if (code == "gbk")
{
str = base64GbkDecode(allstr);
}
else if (code == "utf-8")
{
str = base64Utf8Decode(allstr);
}
return str;
}
// string subjectStr = popMail.Messages[i].Headers.GetHeader("Subject");
//subjectstr = DecodeStr(subjectallstr.Split('?')[3], “utf-8”);
//再次申明下一定要用popMail.Messages[i].Headers.GetHeader(“Subject”)的形式,
//如果原来页面用的是UTF-8编码popMail.Messages[i].Subject得到的将是直接经jmail解码后的乱码
}