/// <summary>
        /// Parses body from the specified stream
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="mediaType">MIME media type. For example: text/plain.</param>
        /// <param name="stream">Stream from where to read body.</param>
        /// <returns>Returns parsed body.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>stream</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static new MIME_b Parse(MIME_Entity owner, string mediaType, SmartStream stream)
        {
            if (owner == null)
            {
                throw new ArgumentNullException("owner");
            }
            if (mediaType == null)
            {
                throw new ArgumentNullException("mediaType");
            }
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (owner.ContentType == null || owner.ContentType.Param_Boundary == null)
            {
                throw new ParseException("Multipart entity has not required 'boundary' paramter.");
            }

            MIME_b_MultipartMixed retVal = new MIME_b_MultipartMixed(owner.ContentType);

            ParseInternal(owner, mediaType, stream, retVal);

            return(retVal);
        }
        /// <summary>
        /// Parses body from the specified stream
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="mediaType">MIME media type. For example: text/plain.</param>
        /// <param name="stream">Stream from where to read body.</param>
        /// <returns>Returns parsed body.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>stream</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static new MIME_b Parse(MIME_Entity owner,string mediaType,SmartStream stream)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(mediaType == null){
                throw new ArgumentNullException("mediaType");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }
            if(owner.ContentType == null || owner.ContentType.Param_Boundary == null){
                throw new ParseException("Multipart entity has not required 'boundary' paramter.");
            }

            MIME_b_MultipartMixed retVal = new MIME_b_MultipartMixed(owner.ContentType);
            ParseInternal(owner,mediaType,stream,retVal);

            return retVal;
        }
Exemple #3
0
        /// <summary>
        /// Generates message parsing failed message.
        /// </summary>
        /// <param name="message">Message stream.</param>
        /// <returns>Returns message parsing failed message.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>message</b> is null reference.</exception>
        public static Mail_Message GenerateBadMessage(Stream message)
        {
            if(message == null){
                throw new ArgumentNullException("message");
            }

            Mail_Message msg = new Mail_Message();
            msg.MimeVersion = "1.0";
            msg.MessageID = MIME_Utils.CreateMessageID();
            msg.Date = DateTime.Now;
            msg.From = new Mail_t_MailboxList();
            msg.From.Add(new Mail_t_Mailbox("system","system"));
            msg.To = new Mail_t_AddressList();
            msg.To.Add(new Mail_t_Mailbox("system","system"));
            msg.Subject = "[BAD MESSAGE] Bad message, message parsing failed !";

            //--- multipart/mixed -------------------------------------------------------------------------------------------------
            MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);
            contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.');
            MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);
            msg.Body = multipartMixed;

                //--- text/plain ---------------------------------------------------------------------------------------------------
                MIME_Entity entity_text_plain = new MIME_Entity();
                MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
                entity_text_plain.Body = text_plain;
                text_plain.SetText(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,"NOTE: Bad message, message parsing failed.\r\n\r\nOriginal message attached as 'data.eml'\r\n");
                multipartMixed.BodyParts.Add(entity_text_plain);

                //--- application/octet-stream --------------------------------------------------------------------------------------
                MIME_Entity entity_application_octet_stream = new MIME_Entity();
                entity_application_octet_stream.ContentDisposition = new MIME_h_ContentDisposition("attachment");
                entity_application_octet_stream.ContentDisposition.Param_FileName = "data.eml";
                MIME_b_Application application_octet_stream = new MIME_b_Application(MIME_MediaTypes.Application.octet_stream);
                entity_application_octet_stream.Body = application_octet_stream;
                application_octet_stream.SetData(message,"base64");
                multipartMixed.BodyParts.Add(entity_application_octet_stream);

            return msg;
        }
Exemple #4
0
		/// <summary>
		/// Stores message to specified folder.
		/// </summary>
        /// <param name="accessingUser">User who accesses this method. 
        /// User needs r permission to call this method or Exception is thrown. 
        /// There is special user 'system' for which permission check is skipped.</param>
        /// <param name="folderOwnerUser">User who's folder it is.</param>
        /// <param name="folder">Folder where to store message. For example: Inbox,Public Folders/Documnets .</param>
		/// <param name="msgStream">Stream where message has stored. Stream position must be at the beginning of the message.</param>
		/// <param name="date">Recieve date.</param>
		/// <param name="flags">Message flags.</param>
		public void StoreMessage(string accessingUser,string folderOwnerUser,string folder,Stream msgStream,DateTime date,IMAP_MessageFlags flags)
		{
            /* Implementation notes:
                *) Validate values. Throw ArgumnetExcetion if invalid values.
                *) Ensure that user exists.
                *) Normalize folder. Remove '/' from folder start and end, ... .
                *) Do Shared Folders mapping.
                *) Ensure that folder exists. Throw Exception if don't.
                *) See if user has sufficient permissions. User requires 'p' or 'i' permission.
                    There is builtin user system, skip ACL for it.
                *) Store message.
            */

            //--- Validate values -------------------//
            ArgsValidator.ValidateUserName(folderOwnerUser);
            ArgsValidator.ValidateFolder(folder);
            ArgsValidator.ValidateNotNull(msgStream);
            //---------------------------------------//

            // Ensure that user exists.
            if(!UserExists(folderOwnerUser)){
                throw new Exception("User '" + folderOwnerUser + "' doesn't exist !");
            }

            // Normalize folder. Remove '/' from folder start and end.
            folder = API_Utlis.NormalizeFolder(folder);

            // Do Shared Folders mapping.
            string originalFolder = folder;
            SharedFolderMapInfo mappedFolder = MapSharedFolder(originalFolder);
            if(mappedFolder.IsSharedFolder){
                folderOwnerUser = mappedFolder.FolderOnwer;
                folder = mappedFolder.Folder;

                if(folderOwnerUser == "" || folder == ""){
                    throw new ArgumentException("Specified root folder '" + originalFolder + "' isn't accessible !");
                }
            }

            // Ensure that folder exists. Throw Exception if don't.
            if(!FolderExists(folderOwnerUser + "/" + folder)){
                throw new Exception("Folder '" + folder + "' doesn't exist !");
            }

            // See if user has sufficient permissions. User requires 'p' or 'i' permission.
            //  There is builtin user system, skip ACL for it.
            if(accessingUser.ToLower() != "system"){
                IMAP_ACL_Flags acl = GetUserACL(folderOwnerUser,folder,accessingUser);
                if((acl & IMAP_ACL_Flags.p) == 0 && (acl & IMAP_ACL_Flags.i) == 0){
                    throw new InsufficientPermissionsException("Insufficient permissions for folder '" + accessingUser + "/" + folder + "' !");
                }
            }

            //--- Store message
            MemoryStream msgMemStream = new MemoryStream();
            Net_Utils.StreamCopy(msgStream,msgMemStream,32000);
	        byte[] messageData = msgMemStream.ToArray();
            byte[] topLines = GetTopLines(new MemoryStream(messageData),50);
            Mail_Message message = null;
            try{
                msgStream.Position = 0;
                message = Mail_Message.ParseFromByte(messageData);
            }
            catch(Exception x){
                message = new Mail_Message();
                message.MimeVersion = "1.0";
                message.MessageID = MIME_Utils.CreateMessageID();
                message.Date = DateTime.Now;
                message.From = new Mail_t_MailboxList();
                message.From.Add(new Mail_t_Mailbox("system","system"));
                message.To = new Mail_t_AddressList();
                message.To.Add(new Mail_t_Mailbox("system","system"));
                message.Subject = "[BAD MESSAGE] Bad message, message parsing failed !";

                //--- multipart/mixed -------------------------------------------------------------------------------------------------
                MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);
                contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.');
                MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);
                message.Body = multipartMixed;

                    //--- text/plain ---------------------------------------------------------------------------------------------------
                    MIME_Entity entity_text_plain = new MIME_Entity();
                    MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
                    entity_text_plain.Body = text_plain;
                    text_plain.SetText(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,"NOTE: Bad message, message parsing failed.\r\n\r\n");
                    multipartMixed.BodyParts.Add(entity_text_plain);
            }
            byte[] envelope = System.Text.Encoding.Default.GetBytes(IMAP_Envelope.ConstructEnvelope(message));
            byte[] body     = System.Text.Encoding.Default.GetBytes(IMAP_BODY.ConstructBodyStructure(message,false));

			using(WSqlCommand sqlCmd = new WSqlCommand(m_ConStr,"lspr_StoreMessage")){
				sqlCmd.AddParameter("_userName"     ,NpgsqlDbType.Varchar   ,folderOwnerUser);
				sqlCmd.AddParameter("_folder"       ,NpgsqlDbType.Varchar   ,folder);
				sqlCmd.AddParameter("_messageID"    ,NpgsqlDbType.Varchar   ,Guid.NewGuid().ToString());
				sqlCmd.AddParameter("_size"         ,NpgsqlDbType.Integer   ,messageData.Length);
				sqlCmd.AddParameter("_messageFlags" ,NpgsqlDbType.Integer   ,(int)flags);
				sqlCmd.AddParameter("_date"         ,NpgsqlDbType.Timestamp ,date);
				sqlCmd.AddParameter("_topLines"     ,NpgsqlDbType.Bytea     ,topLines);
				sqlCmd.AddParameter("_data"         ,NpgsqlDbType.Bytea     ,messageData);
                sqlCmd.AddParameter("_imapEnvelope" ,NpgsqlDbType.Bytea     ,envelope);
                sqlCmd.AddParameter("_imapBody"     ,NpgsqlDbType.Bytea     ,body);

				DataSet ds = sqlCmd.Execute();
			}
		}
Exemple #5
0
        private Mail_Message Create_PlainText_Html_Attachment_Image(string mailTo, string mailFrom, string mailFromDisplay)
        {
            Mail_Message msg = new Mail_Message();
            msg.MimeVersion = "1.0";
            msg.MessageID = MIME_Utils.CreateMessageID();
            msg.Date = DateTime.Now;
            msg.From = new Mail_t_MailboxList();
            msg.From.Add(new Mail_t_Mailbox(mailFromDisplay, mailFrom));
            msg.To = new Mail_t_AddressList();
            msg.To.Add(new Mail_t_Mailbox(mailTo, mailTo));
            msg.Subject = "Test Send Mail";
            //设置回执通知
            //string notifyEmail = SystemConfig.Default.DispositionNotificationTo;
            //if (!string.IsNullOrEmpty(notifyEmail) && ValidateUtil.IsEmail(notifyEmail))
            //{
            //    msg.DispositionNotificationTo = new Mail_t_Mailbox(notifyEmail, notifyEmail);
            //}

            #region MyRegion
            //--- multipart/mixed -----------------------------------
            MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);
            contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
            MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);
            msg.Body = multipartMixed;

            //--- multipart/alternative -----------------------------
            MIME_Entity entity_multipartAlternative = new MIME_Entity();
            MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative);
            contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
            MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative);
            entity_multipartAlternative.Body = multipartAlternative;
            multipartMixed.BodyParts.Add(entity_multipartAlternative);

            //--- text/plain ----------------------------------------
            MIME_Entity entity_text_plain = new MIME_Entity();
            MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
            entity_text_plain.Body = text_plain;

            //普通文本邮件内容,如果对方的收件客户端不支持HTML,这是必需的
            string plainTextBody = "如果你邮件客户端不支持HTML格式,或者你切换到“普通文本”视图,将看到此内容";
            //if (!string.IsNullOrEmpty(SystemConfig.Default.PlaintTextTips))
            //{
            //    plainTextBody = SystemConfig.Default.PlaintTextTips;
            //}

            text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, plainTextBody);
            multipartAlternative.BodyParts.Add(entity_text_plain);

            //--- text/html -----------------------------------------
            string htmlText = "<html>这是一份测试邮件,来自<font color=red><b>厦门至正测试程序</b></font></html>";
            MIME_Entity entity_text_html = new MIME_Entity();
            MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html);
            entity_text_html.Body = text_html;
            text_html.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, htmlText);
            multipartAlternative.BodyParts.Add(entity_text_html);

            //--- application/octet-stream -------------------------
            //foreach (string attach in mailInfo.Attachments)
            //{
            //    multipartMixed.BodyParts.Add(Mail_Message.CreateAttachment(attach));
            //}

            //foreach (string imageFile in mailInfo.EmbedImages)
            //{
            //MIME_Entity entity_image = new MIME_Entity();
            //entity_image.ContentDisposition = new MIME_h_ContentDisposition(MIME_DispositionTypes.Inline);
            //string fileName = "D:\\test.txt"; // DirectoryUtil.GetFileName(imageFile, true);
            //entity_image.ContentID = (new Guid()).ToString().Replace('-', '.'); //BytesTools.BytesToHex(Encoding.Default.GetBytes(fileName));
            //MIME_b_Image body_image = new MIME_b_Image(MIME_MediaTypes.Image.jpeg);
            //entity_image.Body = body_image;
            //body_image.SetDataFromFile("D:\\test.txt", MIME_TransferEncodings.Base64);
            //multipartMixed.BodyParts.Add(entity_image);
            //}

            #endregion

            return msg;
        }
        public void Send(ChannelMessage message)
        {
            var creds = CredentialsProvider.GetCredentials().ToNetworkCredential();

            Mail_Message msg = new Mail_Message();

            msg.MimeVersion = "1.0";
            msg.MessageID = MIME_Utils.CreateMessageID();
            msg.Subject = message.Context;
            msg.From = message.From.ToMailBoxList();
            msg.ReplyTo = message.ReturnTo == null ?
                message.From.ToAddressList() : message.ReturnTo.ToAddressList();

            if (String.IsNullOrEmpty(message.InReplyTo) == false)
                msg.InReplyTo = message.InReplyTo;

            msg.To = new Mail_t_AddressList();
            foreach (var address in message.To)
                msg.To.Add(address.ToMailBox());

            msg.Cc = new Mail_t_AddressList();
            foreach (var address in message.CC)
                msg.Cc.Add(address.ToMailBox());

            //--- multipart/mixed -------------------------------------------------------------------------------------------------
            MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);
            contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
            MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);
            msg.Body = multipartMixed;

            //--- multipart/alternative -----------------------------------------------------------------------------------------
            MIME_Entity entity_multipartAlternative = new MIME_Entity();
            MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative);
            contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
            MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative);
            entity_multipartAlternative.Body = multipartAlternative;
            multipartMixed.BodyParts.Add(entity_multipartAlternative);

            //--- text/plain ----------------------------------------------------------------------------------------------------
            MIME_Entity entity_text_plain = new MIME_Entity();
            MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
            entity_text_plain.Body = text_plain;
            // Add text body if there is any
            if (message.BodyText != null && message.BodyText.Length > 0)
            {
                var bodyText = message.BodyText.ReadString();

                // Make sure there is a newline at the end of our text, otherwise it will screw up
                // our multipart data format
                if (!bodyText.EndsWith(Environment.NewLine))
                    bodyText = bodyText + Environment.NewLine;

                text_plain.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyText);
            }

            multipartAlternative.BodyParts.Add(entity_text_plain);

            //--- text/html ------------------------------------------------------------------------------------------------------
            MIME_Entity entity_text_html = new MIME_Entity();
            MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html);
            entity_text_html.Body = text_html;
            if (message.BodyHtml != null && message.BodyHtml.Length > 0)
            {
                var bodyHtml = message.BodyHtml.ReadString();

                // Make sure there is a newline at the end of our text, otherwise it will screw up
                // our multipart data format
                if (!bodyHtml.EndsWith(Environment.NewLine))
                    bodyHtml = bodyHtml + Environment.NewLine;

                text_html.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyHtml);
            }

            multipartAlternative.BodyParts.Add(entity_text_html);

            foreach (var channelAttachment in message.Attachments)
            {
                MIME_b_Application attachmentBody = new MIME_b_Application(MIME_MediaTypes.Application.octet_stream);
                MIME_Entity attachment = new MIME_Entity();
                attachment.Body = attachmentBody;

                // Has to happen before the following lines of code
                multipartMixed.BodyParts.Add(attachment);

                attachment.ContentType = new MIME_h_ContentType(MimeHelper.GetMimeType(channelAttachment.Filename));
                attachment.ContentType.Param_Name = channelAttachment.Filename;

                MIME_h_ContentDisposition contentDisposition = new MIME_h_ContentDisposition(DispositionTypeNames.Attachment);
                contentDisposition.Param_FileName = channelAttachment.Filename;

                attachment.ContentDisposition = contentDisposition;
                attachment.ContentTransferEncoding = TransferEncoding.Base64.ToString();

                attachmentBody.SetData(channelAttachment.ContentStream, MIME_TransferEncodings.Base64);
            }

            // Inject headers
            if (!String.IsNullOrEmpty(message.MessageIdentifier))
                msg.Header.Add(new MIME_h_Unstructured("x-i2mp-messageid", message.MessageIdentifier));

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpFlow))
            //    msg.Header.Add(new MIME_h_Unstructured("x-i2mp-flow", message.Metadata.i2mpFlow));

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpReference))
            //    mailMessage.Headers.Add("X-i2mp-ref", message.Metadata.i2mpReference);

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpSequence))
            //    mailMessage.Headers.Add("X-i2mp-seq", message.Metadata.i2mpSequence);

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelation))
            //    mailMessage.Headers.Add("X-i2mp-rel", message.Metadata.i2mpRelation);

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelationId))
            //    mailMessage.Headers.Add("X-i2mp-rel-id", message.Metadata.i2mpRelationId);

            // Send message
            try
            {
                SMTP_Client client = new SMTP_Client();

                if ("/Settings/Channels/LoggerEnabled".AsKey(false))
                    client.Logger = new LumiSoft.Net.Log.Logger();

                // todo push this logic into the smtp client implementation itself
                if (Hostname == "smtp.live.com")
                {
                    // Hack for hotmail, first do a connect with no secured channel,
                    // then a STARTTLS
                    client.Connect(Hostname, Port, false);
                    client.StartTLS();
                }
                else
                {
                    client.Connect(Hostname, Port, IsSecured);
                }

                client.Authenticate(creds.UserName, creds.Password);

                using (MemoryStream ms = new MemoryStream())
                {
                    client.MailFrom(msg.From[0].Address, -1);

                    msg.ToStream(ms,
                        new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);

                    // Reset stream
                    ms.Seek(0, SeekOrigin.Begin);

                    foreach (var address in message.To)
                        client.RcptTo(address.Address);

                    foreach (var address in message.CC)
                        client.RcptTo(address.Address);

                    foreach (var address in message.BCC)
                        client.RcptTo(address.Address);

                    try
                    {
                        client.SendMessage(ms);
                    }
                    finally
                    {
                        client.Dispose();
                    }
                }
            }
            catch(SmtpFailedRecipientsException e)
            {
                throw new ChannelFunctionalException(e.Message, e) { DoNotRetry = true };
            }
            catch (SmtpException e)
            {
                throw new ChannelFunctionalException(e.Message, e);
            }
            catch (Exception e)
            {
                throw new ChannelFunctionalException(e.Message, e);
            }
        }
Exemple #7
0
        /// <summary>
        /// Creates Mime message based on UI data.
        /// </summary>
        private Mail_Message CreateMessage()
        {
            Mail_Message msg = new Mail_Message();
            msg.MimeVersion = "1.0";
            msg.MessageID = MIME_Utils.CreateMessageID();
            msg.Date = DateTime.Now;
            msg.From = Mail_h_MailboxList.Parse("From: " + m_pFrom.Text).Addresses;
            msg.To = new Mail_t_AddressList();
            msg.To.Add(new Mail_t_Mailbox(m_pFolder.User.FullName,m_pFolder.User.FullName + "@localhost"));
            msg.Subject = m_pSubject.Text;

            //--- multipart/mixed -------------------------------------------------------------------------------------------------
            MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);
            contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.');
            MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);
            msg.Body = multipartMixed;

                //--- multipart/alternative -----------------------------------------------------------------------------------------
                MIME_Entity entity_multipartAlternative = new MIME_Entity();
                MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative);
                contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.');
                MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative);
                entity_multipartAlternative.Body = multipartAlternative;
                multipartMixed.BodyParts.Add(entity_multipartAlternative);

                    //--- text/plain ----------------------------------------------------------------------------------------------------
                    MIME_Entity entity_text_plain = new MIME_Entity();
                    MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
                    entity_text_plain.Body = text_plain;
                    text_plain.SetText(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,m_pText.Text);
                    multipartAlternative.BodyParts.Add(entity_text_plain);

                    //--- text/html ------------------------------------------------------------------------------------------------------
                    MIME_Entity entity_text_html = new MIME_Entity();
                    MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html);
                    entity_text_html.Body = text_html;
                    text_html.SetText(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,RtfToHtml());
                    multipartAlternative.BodyParts.Add(entity_text_html);
            
            //--- application/octet-stream -----------------------------------------------------------------------------------------------
            foreach(ListViewItem item in m_pAttachments.Items){
                multipartMixed.BodyParts.Add(Mail_Message.CreateAttachment(item.Tag.ToString()));
            }

            return msg;
        }
Exemple #8
0
        private static void CreateBodyPart(Mail_Message msg, string BodyText)
        {
            //--- multipart/mixed -----------------------------------
            MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);
            contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
            MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);
            msg.Body = multipartMixed;

            //--- multipart/alternative -----------------------------
            MIME_Entity entity_multipartAlternative = new MIME_Entity();
            MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative);
            contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
            MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative);
            entity_multipartAlternative.Body = multipartAlternative;
            multipartMixed.BodyParts.Add(entity_multipartAlternative);

            //--- text/plain ----------------------------------------
            MIME_Entity entity_text_plain = new MIME_Entity();
            MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
            entity_text_plain.Body = text_plain;
            entity_text_plain.ContentTransferEncoding = MIME_TransferEncodings.Base64;
            //普通文本邮件内容,如果对方的收件客户端不支持HTML,这是必需的
            string plainTextBody = "如果你邮件客户端不支持HTML格式,或者你切换到“普通文本”视图,将看到此内容";
            //if (!string.IsNullOrEmpty(SystemConfig.Default.PlaintTextTips))
            //{
            //    plainTextBody = SystemConfig.Default.PlaintTextTips;
            //}

            text_plain.SetText(MIME_TransferEncodings.Base64, Encoding.UTF8, plainTextBody);
            multipartAlternative.BodyParts.Add(entity_text_plain);

            //--- text/html -----------------------------------------
            string htmlText = "<html>" + BodyText.Replace("\r\n", "<br>") + "</html>";
            MIME_Entity entity_text_html = new MIME_Entity();
            MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html);
            entity_text_html.Body = text_html;
            text_html.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, htmlText);
            multipartAlternative.BodyParts.Add(entity_text_html);
        }
        /// <summary>
        /// Creates mail message.
        /// </summary>
        /// <param name="from">From: address.</param>
        /// <param name="to">To: address.</param>
        /// <param name="cc">Cc: address. Value null means not used.</param>
        /// <param name="bcc">bcc: address. Value null means not used.</param>
        /// <param name="subject">Message subject.</param>
        /// <param name="text">Message body text.</param>
        /// <param name="html">Message HTML text. Value null means not used.</param>
        /// <param name="attachments">Message attachments. Value null means not used.</param>
        /// <returns>Returns created mail message.</returns>
        public static Mail_Message Create(Mail_t_Mailbox from,Mail_t_Address[] to,Mail_t_Address[] cc,Mail_t_Address[] bcc,string subject,string text,string html,Mail_t_Attachment[] attachments)
        {
            // Create header.
            Mail_Message msg = new Mail_Message();
            msg.MimeVersion = "1.0";
            msg.MessageID = MIME_Utils.CreateMessageID();
            msg.Date = DateTime.Now;
            if(from != null){
                msg.From = new Mail_t_MailboxList();
                msg.From.Add(from);
            }
            if(to != null){
                msg.To = new Mail_t_AddressList();
                foreach(Mail_t_Address address in to){
                    msg.To.Add(address);
                }
            }
            msg.Subject = subject;

            // Create message without attachments.
            if(attachments == null || attachments.Length == 0){
                // text/plain
                if(string.IsNullOrEmpty(html)){
                    MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
                    msg.Body = text_plain;
                    text_plain.SetText(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,text);
                }
                // multipart/alternative
                //  text/plain
                //  text/html
                else{
                    MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative();
                    msg.Body = multipartAlternative;
                        multipartAlternative.BodyParts.Add(MIME_Entity.CreateEntity_Text_Plain(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,text));
                        multipartAlternative.BodyParts.Add(MIME_Entity.CreateEntity_Text_Html(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,html));
                }
            }
            // Create message with attachments.
            else{                
                // multipart/mixed
                //  text/plain
                //  application/octet-stream
                if(string.IsNullOrEmpty(html)){
                    MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed();
                    msg.Body = multipartMixed;
                        multipartMixed.BodyParts.Add(MIME_Entity.CreateEntity_Text_Plain(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,text));

                        // Add attachments.
                        foreach(Mail_t_Attachment attachment in attachments){
                            try{
                                multipartMixed.BodyParts.Add(MIME_Entity.CreateEntity_Attachment(attachment.Name,attachment.GetStream()));
                            }
                            finally{
                                attachment.CloseStream();
                            }
                        }
                }
                // multipart/mixed
                //  multipart/alternative
                //   text/plain
                //   text/html
                //  application/octet-stream
                else{
                    MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed();
                    msg.Body = multipartMixed;
                        MIME_Entity entity_multipart_alternative = new MIME_Entity();
                        MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative();
                        entity_multipart_alternative.Body = multipartAlternative;
                        multipartMixed.BodyParts.Add(entity_multipart_alternative);
                            multipartAlternative.BodyParts.Add(MIME_Entity.CreateEntity_Text_Plain(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,text));
                            multipartAlternative.BodyParts.Add(MIME_Entity.CreateEntity_Text_Html(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,html));

                        // Add attachments.
                        foreach(Mail_t_Attachment attachment in attachments){
                            try{
                                multipartMixed.BodyParts.Add(MIME_Entity.CreateEntity_Attachment(attachment.Name,attachment.GetStream()));
                            }
                            finally{
                                attachment.CloseStream();
                            }
                        }
                }
            }

            return msg;
        }
        /// <summary>
        /// Creates mail message.
        /// </summary>
        /// <param name="signerCert">Signer certificate,</param>
        /// <param name="from">From: address.</param>
        /// <param name="to">To: address.</param>
        /// <param name="cc">Cc: address. Value null means not used.</param>
        /// <param name="bcc">bcc: address. Value null means not used.</param>
        /// <param name="subject">Message subject.</param>
        /// <param name="text">Message body text.</param>
        /// <param name="html">Message HTML text. Value null means not used.</param>
        /// <param name="attachments">Message attachments. Value null means not used.</param>
        /// <returns>Returns created mail message.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>signerCert</b> is null reference.</exception>
        public static Mail_Message Create_MultipartSigned(X509Certificate2 signerCert,Mail_t_Mailbox from,Mail_t_Address[] to,Mail_t_Address[] cc,Mail_t_Address[] bcc,string subject,string text,string html,Mail_t_Attachment[] attachments)
        {
            if(signerCert == null){
                throw new ArgumentNullException("signerCert");
            }

            // Create header.
            Mail_Message msg = new Mail_Message();
            msg.MimeVersion = "1.0";
            msg.MessageID = MIME_Utils.CreateMessageID();
            msg.Date = DateTime.Now;
            if(from != null){
                msg.From = new Mail_t_MailboxList();
                msg.From.Add(from);
            }
            if(to != null){
                msg.To = new Mail_t_AddressList();
                foreach(Mail_t_Address address in to){
                    msg.To.Add(address);
                }
            }
            msg.Subject = subject;

            // Create message without attachments.
            if(attachments == null || attachments.Length == 0){
                // multipart/signed
                //  text/plain
                //  application/pkcs7-signature  MIME library adds this when message saved out.
                if(string.IsNullOrEmpty(html)){
                    MIME_b_MultipartSigned multipartSigned = new MIME_b_MultipartSigned();
                    msg.Body = multipartSigned;
                    multipartSigned.SetCertificate(signerCert);
                        multipartSigned.BodyParts.Add(MIME_Entity.CreateEntity_Text_Plain(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,text));
                }
                // multipart/signed
                //  multipart/alternative
                //   text/plain
                //   text/html
                //  application/pkcs7-signature  MIME library adds this when message saved out.
                else{
                    MIME_b_MultipartSigned multipartSigned = new MIME_b_MultipartSigned();
                    msg.Body = multipartSigned;
                    multipartSigned.SetCertificate(signerCert);
                        MIME_Entity entity_multipart_alternative = new MIME_Entity();
                        MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative();
                        entity_multipart_alternative.Body = multipartAlternative;
                        multipartSigned.BodyParts.Add(entity_multipart_alternative);
                            multipartAlternative.BodyParts.Add(MIME_Entity.CreateEntity_Text_Plain(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,text));
                            multipartAlternative.BodyParts.Add(MIME_Entity.CreateEntity_Text_Html(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,html));
                }                
            }
            // Create message with attachments.
            else{
                // multipart/signed
                //  multipart/mixed
                //   text/plain
                //   application/octet-stream
                //  application/pkcs7-signature  MIME library adds this when message saved out.
                if(string.IsNullOrEmpty(html)){
                    MIME_b_MultipartSigned multipartSigned = new MIME_b_MultipartSigned();
                    msg.Body = multipartSigned;
                    multipartSigned.SetCertificate(signerCert);
                        MIME_Entity entity_multipart_mixed = new MIME_Entity();
                        MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed();
                        entity_multipart_mixed.Body = multipartMixed;
                        multipartSigned.BodyParts.Add(entity_multipart_mixed);
                            multipartMixed.BodyParts.Add(MIME_Entity.CreateEntity_Text_Plain(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,text));

                            // Add attachments.
                            foreach(Mail_t_Attachment attachment in attachments){
                                try{
                                    multipartMixed.BodyParts.Add(MIME_Entity.CreateEntity_Attachment(attachment.Name,attachment.GetStream()));
                                }
                                finally{
                                    attachment.CloseStream();
                                }
                            }
                }
                // multipart/signed
                //  multipart/mixed
                //   multipart/alternative
                //    text/plain
                //    text/html
                //   application/octet-stream
                //  application/pkcs7-signature  MIME library adds this when message saved out.
                else{
                    MIME_b_MultipartSigned multipartSigned = new MIME_b_MultipartSigned();
                    msg.Body = multipartSigned;
                    multipartSigned.SetCertificate(signerCert);
                        MIME_Entity entity_multipart_mixed = new MIME_Entity();
                        MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed();
                        entity_multipart_mixed.Body = multipartMixed;
                        multipartSigned.BodyParts.Add(entity_multipart_mixed);
                            MIME_Entity entity_multipart_alternative = new MIME_Entity();
                            MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative();
                            entity_multipart_alternative.Body = multipartAlternative;
                            multipartMixed.BodyParts.Add(entity_multipart_alternative);
                                multipartAlternative.BodyParts.Add(MIME_Entity.CreateEntity_Text_Plain(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,text));
                                multipartAlternative.BodyParts.Add(MIME_Entity.CreateEntity_Text_Html(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,html));

                            // Add attachments.
                            foreach(Mail_t_Attachment attachment in attachments){
                                try{
                                    multipartMixed.BodyParts.Add(MIME_Entity.CreateEntity_Attachment(attachment.Name,attachment.GetStream()));
                                }
                                finally{
                                    attachment.CloseStream();
                                }
                            }
                }                
            }

            return msg;
        }
Exemple #11
0
        /// <summary>
        /// Generates message missing message.
        /// </summary>
        /// <returns>Returns message missing message.</returns>
        public static Mail_Message GenerateMessageMissing()
        {
            Mail_Message msg = new Mail_Message();
            msg.MimeVersion = "1.0";
            msg.MessageID = MIME_Utils.CreateMessageID();
            msg.Date = DateTime.Now;
            msg.From = new Mail_t_MailboxList();
            msg.From.Add(new Mail_t_Mailbox("system","system"));
            msg.To = new Mail_t_AddressList();
            msg.To.Add(new Mail_t_Mailbox("system","system"));
            msg.Subject = "[MESSAGE MISSING] Message no longer exists on server !";

            //--- multipart/mixed -------------------------------------------------------------------------------------------------
            MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);
            contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-','.');
            MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);
            msg.Body = multipartMixed;

                //--- text/plain ---------------------------------------------------------------------------------------------------
                MIME_Entity entity_text_plain = new MIME_Entity();
                MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
                entity_text_plain.Body = text_plain;
                text_plain.SetText(MIME_TransferEncodings.QuotedPrintable,Encoding.UTF8,"NOTE: Message no longer exists on server.\r\n\r\nMessage is deleted by Administrator or anti-virus software.\r\n");
                multipartMixed.BodyParts.Add(entity_text_plain);

            return msg;
        }