Пример #1
0
        private void WatcherFileCreated(object sender, RenamedEventArgs e)
        {
            try
            {
                MailRequest mailRequst = SerializationUtil.DeSerializeObject <MailRequest>(e.FullPath);
                if (mailRequst == null)
                {
                    return;
                }
                MailMessageWrapper wrapper = new MailMessageWrapper();
                wrapper.filePath    = e.Name;
                wrapper.mailMessage = mailRequst.MailMessage;
                wrapper.mailID      = mailRequst.MailMessageID;
                //Load attachemnts if any
                string attachmentsFolder = @MailSettings.Settings.AttachmentsFolder + "/" + mailRequst.MailMessageID;
                if (Directory.Exists(attachmentsFolder))
                {
                    string[] attachmentPaths = Directory.GetFiles(attachmentsFolder);
                    foreach (string attachmentPath in attachmentPaths)
                    {
                        Stream fileStream = File.OpenRead(@attachmentPath);

                        string     attachmentName = Path.GetFileNameWithoutExtension(attachmentPath);
                        Attachment newAttachment  = new Attachment(fileStream, attachmentName);
                        wrapper.mailMessage.Attachments.Add(newAttachment);

                        //Get attachment name without its ordinal (attachment.txt.1 -> attachment.txt)
                    }
                }

                string linkedResourcesFolder = @MailSettings.Settings.LinkedResourcesFolder + "/" + mailRequst.MailMessageID;
                if (Directory.Exists(linkedResourcesFolder))
                {
                    AlternateView altView             = AlternateView.CreateAlternateViewFromString(wrapper.mailMessage.Body, null, "text/html");
                    string[]      resourceFolderPaths = Directory.GetFiles(linkedResourcesFolder);
                    foreach (string resourcePath in resourceFolderPaths)
                    {
                        Stream         fileStream = File.OpenRead(@resourcePath);
                        string         contentId  = Path.GetFileNameWithoutExtension(resourcePath);
                        LinkedResource rsc        = new LinkedResource(fileStream);
                        rsc.ContentId = contentId;
                        altView.LinkedResources.Add(rsc);
                    }
                    wrapper.mailMessage.AlternateViews.Add(altView);
                }

                mailBuffer.PutMessage(wrapper);
            }
            catch (Exception ex)
            {
                Logger.Instance.Error("Exception occured in MailBuffer.FillBufferWithInitialMessages: ", ex);
                File.Move(e.FullPath, e.FullPath.Replace("temp", "failed"));
            }
        }
Пример #2
0
		public void Send (MailMessage message) 
		{
			EsmtpClient smtp = new EsmtpClient (smtpServer, username, password, use_ssl);
			// wrap the MailMessage in a MailMessage wrapper for easier
			// access to properties and to add some functionality
			MailMessageWrapper messageWrapper = new MailMessageWrapper( message );
			
			smtp.Send (messageWrapper);
			
			smtp.Close ();
		}
Пример #3
0
        private static void cleanUpAttachments(MailMessageWrapper wrapper)
        {
            wrapper.mailMessage.Dispose();
            DirectoryInfo attachmentDir     = new DirectoryInfo(MailSettings.Settings.AttachmentsFolder + "/" + wrapper.mailID);
            DirectoryInfo linkedResourceDir = new DirectoryInfo(MailSettings.Settings.LinkedResourcesFolder + "/" + wrapper.mailID);

            if (attachmentDir.Exists)
            {
                try
                {
                    foreach (FileInfo attachment in attachmentDir.GetFiles())
                    {
                        attachment.Delete();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Instance.Error("Exception in cleanUpAttachments method:", ex);
                }
                try
                {
                    attachmentDir.Delete();
                }
                catch (Exception ex)
                {
                    Logger.Instance.Error("Exception in cleanUpAttachments method:", ex);
                }
            }

            if (linkedResourceDir.Exists)
            {
                try
                {
                    foreach (FileInfo rsc in linkedResourceDir.GetFiles())
                    {
                        rsc.Delete();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Instance.Error("Exception in cleanUpAttachments method on LinkedResource cleanUp:", ex);
                }
                try
                {
                    linkedResourceDir.Delete();
                }
                catch (Exception ex)
                {
                    Logger.Instance.Error("Exception in cleanUpAttachments method on LinkedResource cleanUp:", ex);
                }
            }
        }
Пример #4
0
        public void FillBufferWithInitialMessages()
        {
            var sortedFiles = new DirectoryInfo(@MailSettings.Settings.MailStorageTemp).GetFiles().OrderBy(f => f.LastWriteTime).ToList();

            foreach (var file in sortedFiles)
            {
                try
                {
                    MailRequest        message            = SerializationUtil.DeSerializeObject <MailRequest>(file.FullName);
                    MailMessageWrapper mailMessageWrapper = new MailMessageWrapper();
                    mailMessageWrapper.filePath    = file.Name;
                    mailMessageWrapper.mailMessage = message.MailMessage;
                    mailMessageWrapper.mailID      = message.MailMessageID;
                    mailMessages.Add(mailMessageWrapper);

                    string attachemntsFolder     = @MailSettings.Settings.AttachmentsFolder + "/" + message.MailMessageID;
                    string linkedResourcesFolder = @MailSettings.Settings.LinkedResourcesFolder + "/" + message.MailMessageID;
                    if (Directory.Exists(attachemntsFolder))
                    {
                        string[] attachmentPaths = Directory.GetFiles(attachemntsFolder);
                        foreach (string attachmentPath in attachmentPaths)
                        {
                            Stream fileStream = File.OpenRead(@attachmentPath);
                            //Get attachment name without its ordinal (attachment.txt.1 -> attachment.txt)
                            string     attachmentName = Path.GetFileNameWithoutExtension(attachmentPath);
                            Attachment newAttachment  = new Attachment(fileStream, attachmentName);
                            mailMessageWrapper.mailMessage.Attachments.Add(newAttachment);
                        }
                    }
                    if (Directory.Exists(linkedResourcesFolder))
                    {
                        string[]      linkedResourcesPaths = Directory.GetFiles(linkedResourcesFolder);
                        AlternateView altView = AlternateView.CreateAlternateViewFromString(mailMessageWrapper.mailMessage.Body, null, "text/html");
                        foreach (string rscPath in linkedResourcesPaths)
                        {
                            Stream         fileStream   = File.OpenRead(@rscPath);
                            string         rscContentId = Path.GetFileNameWithoutExtension(rscPath);
                            LinkedResource rsc          = new LinkedResource(fileStream);
                            rsc.ContentId = rscContentId;
                            altView.LinkedResources.Add(rsc);
                        }
                        mailMessageWrapper.mailMessage.AlternateViews.Add(altView);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Instance.Error("Exception occured in MailBuffer.FillBufferWithInitialMessages: ", ex);
                    File.Move(file.FullName, file.FullName.Replace("temp", "failed"));
                }
            }
        }
Пример #5
0
        private static void DeliverMessage(Object mailBuffer)
        {
            while (true)
            {
                MailMessageWrapper mailMessageWrapper = ((MailBuffer)mailBuffer).TakeMessage();
                MailMessage        message            = mailMessageWrapper.mailMessage;



                int        maxRetryCount = MailSettings.Settings.MaxRetryCount;
                SmtpClient smtpClient    = null;
                try
                {
                    smtpClient = new SmtpClient();
                }
                catch (Exception ex)
                {
                    Logger.Instance.Fatal("SMTPClient error:", ex);
                }
                do
                {
                    try
                    {
                        smtpClient.Send(message);
                        File.Move(MailSettings.Settings.MailStorageTemp + "/" + mailMessageWrapper.filePath, MailSettings.Settings.MailStorageSuccess + "/" + mailMessageWrapper.filePath);

                        //success
                        Logger.Instance.Info("Successfully sent mail:" + message.Subject);
                        break;
                    }
                    catch (Exception ex)
                    {
                        if (maxRetryCount <= 0)
                        {
                            Logger.Instance.Error("Failed to send message with subject:" + message.Subject, ex);
                            File.Move(MailSettings.Settings.MailStorageTemp + "/" + mailMessageWrapper.filePath, MailSettings.Settings.MailStorageFailed + "/" + mailMessageWrapper.filePath);
                            break;
                        }
                        else
                        {
                            Logger.Instance.Warn(String.Format("Sending of message failed, retrying {0} more times", maxRetryCount), ex);
                            Thread.Sleep(retryTimeout);
                        }
                    }
                } while (maxRetryCount-- > 0);
                //Clean up attachments (if any) and dispose of mail message
                cleanUpAttachments(mailMessageWrapper);
            }
        }
	public void Send( MailMessageWrapper msg ) {
	    
	    if( msg.From == null ) {
		throw new SmtpException( "From property must be set." );
	    }

	    if( msg.To == null ) {
		if( msg.To.Count < 1 ) throw new SmtpException( "Atleast one recipient must be set." );
	    }
	    
	    	    
	    // start with a reset incase old data
	    // is present at the server in this session
	    smtp.WriteRset();
	    
	    // write the mail from command
	    smtp.WriteMailFrom( msg.From.Address );
	    
	    // write the rcpt to command for the To addresses
	    foreach( MailAddress addr in msg.To ) {
		smtp.WriteRcptTo( addr.Address );
	    }

	    // write the rcpt to command for the Cc addresses
	    foreach( MailAddress addr in msg.Cc ) {
		smtp.WriteRcptTo( addr.Address );
	    }

	    // write the rcpt to command for the Bcc addresses
	    foreach( MailAddress addr in msg.Bcc ) {
		smtp.WriteRcptTo( addr.Address );
	    }
	    
	    // write the data command and then
	    // send the email
	    smtp.WriteData();
		
	    if( msg.Attachments.Count == 0 ) {
		SendSinglepartMail( msg );	    
	    } else {
		
		SendMultipartMail( msg );
	    
	    }

	    // write the data end tag "."
	    smtp.WriteDataEndTag();

	}
Пример #7
0
        public Guid SendEmailMessage(MailMessage mailMessage)
        {
            var mailMessageWrap = new MailMessageWrapper(mailMessage);

            var queuedEmail = new QueuedEmail
            {
                Priority     = 5,
                ToAddress    = mailMessage.To[0].Address,
                ToName       = mailMessage.To[0].DisplayName,
                Subject      = mailMessage.Subject,
                MailMessage  = mailMessageWrap.ToString(),
                CreatedOnUtc = DateTime.UtcNow
            };

            Insert(queuedEmail);

            return(queuedEmail.Id);
        }
Пример #8
0
 public void PutMessage(MailMessageWrapper mailMessage)
 {
     mailMessages.Add(mailMessage);
 }
	// sends a multipart mail to the server
	private void SendMultipartMail( MailMessageWrapper msg ) {
	    	    
	    // generate the boundary between attachments
	    string boundary = MailUtil.GenerateBoundary();
		
	    // set the Content-Type header to multipart/mixed
	    string bodyContentType = msg.Header.ContentType;

	    msg.Header.ContentType = 
		System.String.Format( "multipart/mixed;\r\n   boundary={0}" , boundary );
		
	    // write the header
	    smtp.WriteHeader( msg.Header );
		
	    // write the first part text part
	    // before the attachments
	    smtp.WriteBoundary( boundary );
		
	    MailHeader partHeader = new MailHeader();
	    partHeader.ContentType = bodyContentType;		

	    smtp.WriteHeader( partHeader );
	  
	    // FIXME: probably need to use QP or Base64 on everything higher
	    // then 8-bit .. like utf-16
	    smtp.WriteBytes( msg.BodyEncoding.GetBytes( msg.Body )  );

	    smtp.WriteBoundary( boundary );

	    // now start to write the attachments
	    
	    for( int i=0; i< msg.Attachments.Count ; i++ ) {
		MailAttachment a = (MailAttachment)msg.Attachments[ i ];
			
		FileInfo fileInfo = new FileInfo( a.Filename );

		MailHeader aHeader = new MailHeader();
		
		aHeader.ContentType = 
		    String.Format (MimeTypes.GetMimeType (fileInfo.Name) + "; name=\"{0}\"",fileInfo.Name);
		
		aHeader.ContentDisposition = 
		    String.Format( "attachment; filename=\"{0}\"" , fileInfo.Name );
		
		aHeader.ContentTransferEncoding = a.Encoding.ToString();
		    		
		smtp.WriteHeader( aHeader );
		   
		// perform the actual writing of the file.
		// read from the file stream and write to the tcp stream
		FileStream ins = fileInfo.OpenRead ();
		
		// create an apropriate encoder
		IAttachmentEncoder encoder;
		if( a.Encoding == MailEncoding.UUEncode ) {
		    encoder = new UUAttachmentEncoder( 644 , fileInfo.Name  );
		} else {
		    encoder = new Base64AttachmentEncoder();
		}
		
		encoder.EncodeStream( ins , smtp.Stream );
		
		ins.Close();
		
		    
		smtp.WriteLine( "" );
		
		// if it is the last attachment write
		// the final boundary otherwise write
		// a normal one.
		if( i < (msg.Attachments.Count - 1) ) { 
		    smtp.WriteBoundary( boundary );
		} else {
		    smtp.WriteFinalBoundary( boundary );
		}
		    
	    }
	       
	}
Пример #10
0
	// sends a single part mail to the server
	private void SendSinglepartMail( MailMessageWrapper msg ) {
	    	    	    
	    // write the header
	    smtp.WriteHeader( msg.Header );
	    
	    // send the mail body
	    smtp.WriteBytes( msg.BodyEncoding.GetBytes( msg.Body ) );

	}
Пример #11
0
        public MailMessage GetMailMessage()
        {
            var wrap = MailMessageWrapper.Create(MailMessage);

            return(wrap.ToMailMessage());
        }