摘要: 1、在使用WebService时我们经常会考虑以下问题:怎么防止别人访问我的WebService? 在System.Net中提供了一个NetworkCredential,只有获得该凭证的用户才能访问相应的服务的权限。在NetworkCredential中,我们通过提供WebService发布所在的... 阅读全文
posted @ 2014-06-16 14:32 PEPE YU 阅读(508) 评论(0) 推荐(0) 编辑

一、故事

 

      首先通过CDO.Message来获取邮件EML相关数据:邮件标题、邮件内容、邮件附件、发件人、收件人、CC主要就这么几个,其次通过MailMessage来组织邮件通过Python来发送邮件!

  

     就这么简简单单的需求!!问题出现了,中文附件名!Web打开始终是乱码!使用邮件客户端FireFox是OK的,查看了FireFox源码发现是乱码,这点说明FireFox的强大,非常强大!

    

Content-Type: application/octet-stream; name=鎶ラ攢鍗昪s.xlsx
Content-Transfer-Encoding: base64
Content-Disposition: attachment

  见图见图

 

 

……

二、折腾中

 

     出了问题想办法,一定要抱着始终相信一定可以解决的尤其是搞IT的一定有方法!大事化小,小事化无。先找卧底!第一个想到的便是CDO.Message那就从他下手。最后发现他是平民!

 

     先说说走的路,干货的路,其他摸索的方法想了下数数应该有4,5种了:

    读取EML转换成流,再获取附件再解码,发现中文名OK

     先看结果

    

    再看看代码

    

public class AttachmentExtractor
    {
        private static int imageCount;

        public static void Method(string path)
        {
            StreamReader reader = null;
            try
            {
                reader = new StreamReader(path);
                string line;
                StringBuilder sb = new StringBuilder();
                while ((line = reader.ReadLine()) != null)
                {
                    sb.Append(line.ToLower());
                    if (line.ToLower().StartsWith("content-disposition:attachment;") || line.ToLower().StartsWith("content-disposition: attachment;")) // found attachment 
                    { 
                        string fileName = GetAttachment(reader, line);
                        fileName = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(fileName.Replace("=?utf-8?B?", "").Replace("?=", ""))); 
                    }
                    if (line.ToLower().StartsWith("content-type:image/")) // found embedded image
                    {
                        ExtractContent(reader, GetImage(reader, line));
                    }
                }
            }
            catch (IOException)
            {
                Console.WriteLine("找不到文件!");
            }
            finally
            {
                if (reader != null) reader.Close();
            }

        }

        private static string GetAttachment(TextReader reader, string line)
        {
            if (!line.Contains("filename"))
            {
                line = reader.ReadLine(); // Thunderbird: filename start at
                //second line
            }
            return GetFilenameNew(reader, line);
        }

        private static string GetImage(TextReader reader, string line)
        {
            if (!line.Contains("name"))
            {
                line = reader.ReadLine(); // Thunderbird: filename start at
                //second line
            }
            if (!line.Contains("name")) // embedded image does not have name
            {
                AdvanceToEmptyLine(reader);

                return "image" + imageCount++ + ".jpg"; // default to jpeg
            }

            return GetFilename(reader, line);
        }

        private static string GetFilename(TextReader reader, string line)
        {
            string filename;
            int filenameStart = line.IndexOf('"') + 1;

            if (filenameStart > 0)
            {
                filename = line.Substring(filenameStart, line.Length -
                filenameStart - 1);
            }
            else // filename does not have quote
            {
                filenameStart = line.IndexOf('=') + 1;
                filename = line.Substring(filenameStart, line.Length -
                filenameStart);
            }

            AdvanceToEmptyLine(reader);

            return filename;
        }

        private static string GetFilenameNew(TextReader reader, string line)
        {
            string filename;
            int filenameStart = line.IndexOf('"') + 1;

            if (filenameStart > 0)
            {
                filename = line.Substring(filenameStart, line.Length -
                filenameStart - 1);
            }
            else // filename does not have quote
            {
                filenameStart = line.IndexOf('=') + 1;
                filename = line.Substring(filenameStart, line.Length -
                filenameStart);
            } 

            return filename;
        }

        private static void AdvanceToEmptyLine(TextReader reader)
        {
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                if (String.IsNullOrEmpty(line)) break;
            }
        }

        private static void ExtractContent(TextReader reader, string filename)
        {
            string line;
            var content = new StringBuilder();

            while ((line = reader.ReadLine()) != null)
            {
                if (String.IsNullOrEmpty(line)) break;

                content.Append(line);
            }

            if (content.Length > 0)
            {
                byte[] buffer = Convert.FromBase64String(content.ToString());
                #region 7.7
                if (!File.Exists(filename))
                {
                    return;
                } 
                #endregion
                using (Stream writer = new FileStream(filename,
                FileMode.Create))
                {
                    writer.Write(buffer, 0, buffer.Length);
                }
            }
        }
    }
public RedEmail()
        {
            InitializeComponent();
            this.txtEmailPath.Text = "C:\\Users\\Administrator\\Desktop\\4a3266e6-23bd-11e5-9703-0050569a7cc2.eml";

            AttachmentExtractor.Method(txtEmailPath.Text);
        }

 

   仔细看完代码会发现获取的附件名是编码过的,需要截取。这个要注意!发现经常不写写,不说说都不知道如何表达我那被困的感受!!!不过!有结果就是胜利!如下:

   可喜的是,我找到了原因:CDO.Message不是卧底!是个良民!!!他只是一个善良的二道贩子!

 

三、看到曙光

    好了,总共就两人,一个平民了,那么另一个一定是卧底咯-MailMessage

    先看胜利的结果,这个喜悦之情那!!

    

   一个是EML里面的附件-乱码,一个是通过改良后代码上传上去的-OK……(ps 写博客都不忘给我老婆店铺做广告,主要是因为我们博客园老牛B了,经常会被其他网站转载,又不写转载信息!

   搞IT的代码最直接看看代码,如下:   

                //MemoryStream ms =
                //    new MemoryStream(File.ReadAllBytes(@"C:\\Users\\Administrator\\Desktop\\RDP_需求规格说明书.docx"));
                ////message.Attachments.Add(new System.Net.Mail.Attachment(ms, "RDP_需求规格说明书.docx"));

                //System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
                //System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
                //attach.ContentDisposition.FileName = "产品经理2.docx";
                 
                //attach.NameEncoding = Encoding.GetEncoding("utf-8"); 
                //      `message.Attachments.Add(attach);

                System.Net.Mail.Attachment attachment = AttachmentHelper.CreateAttachment(@"C:\\Users\\Administrator\\Desktop\\产品经理2.jpg", "产品经理2.jpg", TransferEncoding.Base64);

                message.Attachments.Add(attachment);
                //var attachment = new Attachment(new MemoryStream(File.ReadAllBytes(@"C:\\Users\\Administrator\\Desktop\\产品经理2.jpg")), new System.Net.Mime.ContentType("application/vnd.ms-excel"));
                ////bool flag = File.Exists(@"C:\\Users\\Administrator\\Desktop\\产品经理2.jpg");
                //FileStream fs = new FileStream(@"C:\\Users\\Administrator\\Desktop\\产品经理2.jpg", FileMode.Open, FileAccess.Read);
                //System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
                //System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(fs, ct);
                //attach.ContentDisposition.FileName =  "产品经理2.jpg";
                //fs.Close();
                //message.Attachments.Add(attach);   

看到了么!注释的就是实验的!我说我是折腾了半天解决的!

  好了,揭开神秘的面纱AttachmentHelper  

 public class AttachmentHelper
    {
        public static System.Net.Mail.Attachment CreateAttachment(string attachmentFile, string displayName, TransferEncoding transferEncoding)
        {
            System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(attachmentFile);
            attachment.TransferEncoding = transferEncoding;

            string tranferEncodingMarker = String.Empty;
            string encodingMarker = String.Empty;
            int maxChunkLength = 0;

            switch (transferEncoding)
            {
                case TransferEncoding.Base64:
                    tranferEncodingMarker = "B";
                    encodingMarker = "UTF-8";
                    maxChunkLength = 30;
                    break;
                case TransferEncoding.QuotedPrintable:
                    tranferEncodingMarker = "Q";
                    encodingMarker = "ISO-8859-1";
                    maxChunkLength = 76;
                    break;
                default:
                    throw (new ArgumentException(String.Format("The specified TransferEncoding is not supported: {0}", transferEncoding, "transferEncoding")));
            }

            attachment.NameEncoding = Encoding.GetEncoding(encodingMarker);

            string encodingtoken = String.Format("=?{0}?{1}?", encodingMarker, tranferEncodingMarker);
            string softbreak = "?=";
            string encodedAttachmentName = encodingtoken;

            if (attachment.TransferEncoding == TransferEncoding.QuotedPrintable)
                encodedAttachmentName = HttpUtility.UrlEncode(displayName, Encoding.Default).Replace("+", " ").Replace("%", "=");
            else
                encodedAttachmentName = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(displayName));

            encodedAttachmentName = SplitEncodedAttachmentName(encodingtoken, softbreak, maxChunkLength, encodedAttachmentName);
            attachment.Name = encodedAttachmentName;

            return attachment;
        }

        private static string SplitEncodedAttachmentName(string encodingtoken, string softbreak, int maxChunkLength, string encoded)
        {
            int splitLength = maxChunkLength - encodingtoken.Length - (softbreak.Length * 2);
            var parts = SplitByLength(encoded, splitLength);

            string encodedAttachmentName = encodingtoken;

            foreach (var part in parts)
                encodedAttachmentName += part + softbreak + encodingtoken;

            encodedAttachmentName = encodedAttachmentName.Remove(encodedAttachmentName.Length - encodingtoken.Length, encodingtoken.Length);
            return encodedAttachmentName;
        }

        private static IEnumerable<string> SplitByLength(string stringToSplit, int length)
        {
            while (stringToSplit.Length > length)
            {
                yield return stringToSplit.Substring(0, length);
                stringToSplit = stringToSplit.Substring(length);
            }

            if (stringToSplit.Length > 0) yield return stringToSplit;
        }
    }

这个牛B的类不是我写的!声明下!我可没那么牛×,是哥千辛万苦+输入了英文才找到的!更坚定了我要学好英文的夙愿!!!!

 

 

四、后话

    好了,可以安心改改代码,发布一个Demo了。

 

    总结下:

     1、要有不放弃不抛弃。

     2、要敢自我调侃的娱乐精神。

     3、关键时刻别忘了Google,国外的月亮有时候真的比国内圆!

 

一口气,好了,我去WC 憋死我了………………

 

posted @ 2015-07-09 11:02 PEPE YU 阅读(2838) 评论(3) 推荐(1) 编辑
摘要: (function ($) { var promoter = promoter || {}; promoter.utils = (function () { var controller = "../promoter"; var pro = function ... 阅读全文
posted @ 2015-06-08 16:11 PEPE YU 阅读(301) 评论(0) 推荐(0) 编辑
摘要: MySqlHelper类 /// ///MySql操作类 /// public abstract class MySqlHelper { //数据库连接字符串 public static string Conn = "Database='... 阅读全文
posted @ 2015-05-19 17:10 PEPE YU 阅读(433) 评论(0) 推荐(0) 编辑
摘要: EML格式是微软公司在Outlook中所使用的一种遵循RFC822及其后续扩展的文件格式,并成为各类电子邮件软件的通用格式。 做个笔记,C# 邮件处理保存为eml格式; 一、网上好多这样的写法,可以在.net formwork4.5里面 百试不爽………… /// /// 2.0可... 阅读全文
posted @ 2015-05-19 14:08 PEPE YU 阅读(790) 评论(0) 推荐(0) 编辑
摘要: 1、C#调用URL接口 /// /// 处理中心 /// /// /// 路径 /// 账号 /// 公司名 /// 创建时间 /// /// 大小 ... 阅读全文
posted @ 2015-05-18 15:15 PEPE YU 阅读(326) 评论(0) 推荐(0) 编辑
摘要: 1:如何新起线程 新起一个线程的方法,可以使用Thread,BackgroundWorker ,ThreadPool,控件.BeginInvoke,委托.BeginInvoke,Timer。2:异步调用返回值上码:using System;using System.Collections.Gene... 阅读全文
posted @ 2015-05-15 16:45 PEPE YU 阅读(635) 评论(1) 推荐(0) 编辑
摘要: a、多线程可以说是实现异步的一种方式; b、共同点:多线程和异步操作两者都可以达到避免调用线程阻塞的目的,从而提高软件的可响应性; c、线程消费CPU资源、 异步消费硬件资源;1、多线程和异步操作的异同 多线程和异步操作两者都可以达到避免调用线程阻塞的目的,从而提高软件的可响应性。甚至有些... 阅读全文
posted @ 2015-05-14 16:04 PEPE YU 阅读(1837) 评论(5) 推荐(1) 编辑
摘要: 一、先贴错误 因为这个笔记主要记录我如何整好这个OBS源码环境的,给需要的童鞋一个参考 1.1、#include 报错 没有这个 解决方案:把2,3先解决了就水到渠成 1.2、安装DirectX报错: Setup failed Errors were encountered during... 阅读全文
posted @ 2015-05-13 15:52 PEPE YU 阅读(1876) 评论(0) 推荐(0) 编辑
摘要: 项目中的文件需要保存到网络存储设备中,之前用的是NAS。因没来得及采购就先用Samba顶上。代码发现通用……一、定义: Samba是在Linux和UNIX系统上实现SMB协议的一个免费软件,由服务器及客户端程序构成。SMB(Server Messages Block,信息服务块)是一... 阅读全文
posted @ 2015-04-14 09:54 PEPE YU 阅读(3200) 评论(2) 推荐(0) 编辑
摘要: 通过CMD注册Windows服务 之前一直这样写一直也是注册成功,今天却遇到了问题SC Manager 失败 sc create RenService binPath= C:\Tools\StateAndRestartService\VNCSelf.WindowsService.ex... 阅读全文
posted @ 2015-04-13 16:43 PEPE YU 阅读(1385) 评论(0) 推荐(0) 编辑
点击右上角即可分享
微信分享提示