发邮件窗体【支持编辑邮件模板,使用wse多线程上传附件及发邮件(带附件)】以及在服务器端自动发邮件

        这是前段时间做的一个邮件客户端,支持自定义模板(模板是内置的,固定好了)   
       其中配置模板的xml
<?xml version="1.0" encoding="utf-8" ?>
<TemplateConfigure>
  <BaseDirectory>EmailTemplate</BaseDirectory>

  <TemplateDirectory>模板</TemplateDirectory>

  <AttachDirectory>附件</AttachDirectory>
  
     <Template>
    <EmailType>DrawFail</EmailType>
    <TemplateName>支取缺材料.htm</TemplateName>
 <FileName>DrawFail.htm</FileName>
  </Template>

  <Attach>
    <AttachType>SheBaoBJBack</AttachType>
    <FileName>社保报减退回原因释义表.doc</FileName>
  </Attach>

  </TemplateConfigure>
读取配置文件的代码为

 private void ParseConfiguration()
        
{
            
try
            
{
                XmlSerializer serializer 
= new XmlSerializer(typeof(TemplateConfigure));
                
using (Stream stream = this.GetType().Assembly.
                    GetManifestResourceStream(
this.GetType(), "EmailTemplate.EmailType.xml"))
                
{
                    templateConfigure 
= serializer.Deserialize(stream) as TemplateConfigure;
                    templateConfigure.TemplateDirectory 
= GetDirectory(templateConfigure.TemplateDirectory);
                    templateConfigure.AttachDirectory 
= GetDirectory(templateConfigure.AttachDirectory);
                }

            }

            
catch (Exception ex)
            
{
                
throw ex;
            }

        }

上传文件使用了wse3.0(web service Enhancements ),使用backgroudworker多线程上传   
启动服务器段wse需在web.config里添加
<webServices>
      <soapServerProtocolFactory type="Microsoft.Web.Services3.WseProtocolFactory, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      <soapExtensionImporterTypes>
        <add type="Microsoft.Web.Services3.Description.WseExtensionImporter, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      </soapExtensionImporterTypes>
    </webServices>


<microsoft.web.services3>
    <messaging>
      <mtom serverMode="Always"/>
    </messaging>
  </microsoft.web.services3>
  

服务器端主要代码为

[WebMethod]
        
public void AppendChunk(string FileName, byte[] buffer, long Offset)
        
{
            
string FilePath = Path.Combine(_uploadPath, FileName);
            
if (Offset == 0)
            
{
                File.Create(FilePath).Close();
            }

            
using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
            
{
                fs.Seek(Offset, SeekOrigin.Begin);
                fs.Write(buffer, 
0, buffer.Length);
            }

        }

客户段使用backgroudworker上传文件
protected override void OnDoWork(DoWorkEventArgs e)
        
{
            
try
            
{
                
long webConfigSetting = this.WebService.GetMaxRequestLength();
                
this.MaxRequestLength = Math.Max(1, (webConfigSetting * 1024- (2 * 1024));
            }

            
catch
            
{
                
this.MaxRequestLength = 4000;
            }

            
base.OnDoWork(e);

            
this.Offset = Int64.Parse(e.Argument.ToString());
            
int numIterations = 0;
            
this.LocalFileName = Path.GetFileName(this.LocalFilePath);
            
if (this.AutoSetChunkSize)
                
this.ChunkSize = 16 * 1024;

            
if (!File.Exists(LocalFilePath))
                
throw new Exception(String.Format("找不到文件{0}", LocalFilePath));

            
long FileSize = new FileInfo(LocalFilePath).Length;
            
string FileSizeDescription = CalcFileSize(FileSize);
            
byte[] Buffer = new byte[ChunkSize];

            
using (FileStream fs = new FileStream(this.LocalFilePath, FileMode.Open, FileAccess.Read))
            
{
                fs.Position 
= this.Offset;
                
int BytesRead;
                
do
                
{
                    BytesRead 
= fs.Read(Buffer, 0, ChunkSize);

                    
if (BytesRead != Buffer.Length)
                    
{
                        
this.ChunkSize = BytesRead;
                        
byte[] TrimmedBuffer = new byte[BytesRead];
                        Array.Copy(Buffer, TrimmedBuffer, BytesRead);
                        Buffer 
= TrimmedBuffer;
                    }

                    
if (Buffer.Length == 0)
                        
break;
                    
try
                    
{
                        
this.WebService.AppendChunk(this.LocalFileName, Buffer, this.Offset);

                        
if (this.AutoSetChunkSize)
                        
{
                            
int currentIntervalMod = numIterations % this.ChunkSizeSampleInterval;
                            
if (currentIntervalMod == 0)
                                
this.StartTime = DateTime.Now;
                            
else if (currentIntervalMod == 1)
                            
{
                                
this.CalcAndSetChunkSize();
                                Buffer 
= new byte[this.ChunkSize];
                            }

                        }

                        
this.Offset += BytesRead;
                        
string SummaryText = String.Format("传输 {0} / {1}", CalcFileSize(this.Offset), FileSizeDescription);
                        
this.ReportProgress((int)(((decimal)Offset / (decimal)FileSize) * 100), SummaryText);
                    }

                    
catch (Exception ex)
                    
{
                        Debug.WriteLine(
"Exception: " + ex.ToString());

                        fs.Position 
-= BytesRead;

                        
if (NumRetries++ >= MaxRetries)
                        
{
                            fs.Close();
                            
throw new Exception(String.Format("上传文件失败! \n{0}", ex.ToString()));
                        }

                    }

                    numIterations
++;
                }
 while (BytesRead > 0 && !this.CancellationPending);
            }

        }
发送邮件的代码为:
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();

                
if (string.IsNullOrEmpty(from))
                
{
                    from 
= ConfigurationManager.AppSettings["FailEmail"];
                }


                mailMessage.From 
= new System.Net.Mail.MailAddress(from);

                mailMessage.To.Add(to);

                
if (!string.IsNullOrEmpty(bcc))
                
{
                    mailMessage.Bcc.Add(bcc);
                }


                mailMessage.Subject 
= subject;

                mailMessage.IsBodyHtml 
= isBodyHtml;

                
//附件
                if (attach != null)
                
{
                    
string directory = GetDirectory();
                    
string filePath = string.Empty;
                    
string cid = string.Empty;
                    System.Net.Mail.Attachment attachment 
= null;
                    
int i = 0;
                    
foreach (string path in attach)
                    
{
                        
if (!string.IsNullOrEmpty(path))
                        
{
                            filePath 
= Path.Combine(directory, Path.GetFileName(path));
                            MemoryStream ms 
= new MemoryStream(File.ReadAllBytes(filePath));
                            attachment 
= new System.Net.Mail.Attachment(ms, Path.GetFileName(filePath));
                            
if (content.Contains(path))
                            
{
                                cid 
= String.Format("image_{0}", i);
                                attachment.ContentId 
= cid;
                                attachment.Name 
= Path.GetFileNameWithoutExtension(path);
                                content 
= content.Replace(path, String.Format("cid:{0}", cid));
                                i
++;
                            }

                            mailMessage.Attachments.Add(attachment);
                        }

                    }

                }


                mailMessage.Body 
= content;

                SmtpClient.Send(mailMessage);

其中参考了CodeProject上的很多代码,不过不知道具体的地址了,而且懒得去找了。
关于自动发邮件参考了community server 的Job模块(具体实现参考代码,做的很简陋)
先附上代码/Files/believe3301/Code.rar
第三方程序集/Files/believe3301/Libs.rar,其中用到了DevExpress的Dll文件太大了所以就不上传了,出现编译错误请下载wse3.0和安装dev
posted @ 2008-07-12 08:46  TG.Yang's IT Space  阅读(1949)  评论(6编辑  收藏  举报