Beispiel #1
0
        public void Deserialize(System.IO.TextReader rdr, Serializer serializer)
        {
            string name, value;
            var    parameters = new System.Collections.Specialized.NameValueCollection();

            while (rdr.Property(out name, out value, parameters) && !string.IsNullOrEmpty(name))
            {
                switch (name.ToUpper())
                {
                case "BEGIN":
                    switch (value)
                    {
                    case "VALARM":
                        var a = serializer.GetService <Alarm>();
                        a.Deserialize(rdr, serializer);
                        Alarms.Add(a);
                        break;
                    }
                    break;

                case "ATTENDEE":
                    var contact = new Contact();
                    contact.Deserialize(value, parameters);
                    Attendees.Add(contact);
                    break;

                case "CATEGORIES":
                    Categories = value.SplitEscaped().ToList();
                    break;

                case "CLASS": Class = value.ToEnum <Classes>(); break;

                case "CREATED": Created = value.ToDateTime(); break;

                case "DESCRIPTION": Description = value; break;

                case "DTEND": End = value.ToDateTime(); break;

                case "DTSTAMP": DTSTAMP = value.ToDateTime().GetValueOrDefault(); break;

                case "DTSTART": Start = value.ToDateTime(); break;

                case "LAST-MODIFIED": LastModified = value.ToDateTime(); break;

                case "LOCATION": Location = value; break;

                case "ORGANIZER":
                    Organizer = serializer.GetService <Contact>();
                    Organizer.Deserialize(value, parameters);
                    break;

                case "PRIORITY": Priority = value.ToInt(); break;

                case "SEQUENCE": Sequence = value.ToInt(); break;

                case "STATUS": Status = value.ToEnum <Statuses>(); break;

                case "SUMMARY": Summary = value; break;

                case "TRANSP": Transparency = value; break;

                case "UID": UID = value; break;

                case "URL": Url = value.ToUri(); break;

                case "ATTACH":
                    var attach = value.ToUri();
                    if (attach != null)
                    {
                        Attachments.Add(attach);
                    }
                    break;

                case "RRULE":
                    var rule = serializer.GetService <Recurrence>();
                    rule.Deserialize(null, parameters);
                    Recurrences.Add(rule);
                    break;

                case "END": return;

                default:
                    Properties.Add(Tuple.Create(name, value, parameters));
                    break;
                }
            }

            IsAllDay = Start == End;
        }
Beispiel #2
0
 /// <summary>
 /// Add attachment.
 /// </summary>
 /// <param name="path">Path to the file.</param>
 public void AddAttachment(String path)
 {
     Attachments.Add(new Attachment(path));
 }
Beispiel #3
0
 public void AddAttachment(TaskAttachment taskAttachment)
 {
     Attachments.Add(taskAttachment);
 }
Beispiel #4
0
        private async Task MailHandler(object Sender, MessageEventArgs e)
        {
            string         ContentType  = XML.Attribute(e.Content, "contentType");
            string         MessageId    = XML.Attribute(e.Content, "id");
            int            Priority     = XML.Attribute(e.Content, "priority", 3);
            DateTimeOffset Date         = XML.Attribute(e.Content, "date", DateTimeOffset.Now);
            string         FromMail     = XML.Attribute(e.Content, "fromMail");
            string         FromHeader   = XML.Attribute(e.Content, "fromHeader");
            string         Sender2      = XML.Attribute(e.Content, "sender");
            int            Size         = XML.Attribute(e.Content, "size", 0);
            string         MailObjectId = XML.Attribute(e.Content, "cid");
            List <KeyValuePair <string, string> > Headers     = new List <KeyValuePair <string, string> >();
            List <EmbeddedObjectReference>        Attachments = null;
            List <EmbeddedObjectReference>        Inline      = null;

            foreach (XmlNode N in e.Content.ChildNodes)
            {
                if (N is XmlElement E)
                {
                    switch (E.LocalName)
                    {
                    case "headers":
                        foreach (XmlNode N2 in E.ChildNodes)
                        {
                            switch (N2.LocalName)
                            {
                            case "header":
                                string Key   = XML.Attribute((XmlElement)N2, "name");
                                string Value = N2.InnerText;

                                Headers.Add(new KeyValuePair <string, string>(Key, Value));
                                break;
                            }
                        }
                        break;

                    case "attachment":
                    case "inline":
                        string ContentType2     = XML.Attribute(E, "contentType");
                        string Description      = XML.Attribute(E, "description");
                        string FileName         = XML.Attribute(E, "fileName");
                        string Name             = XML.Attribute(E, "name");
                        string ContentId        = XML.Attribute(E, "id");
                        string EmbeddedObjectId = XML.Attribute(E, "cid");
                        int    Size2            = XML.Attribute(E, "size", 0);

                        EmbeddedObjectReference Ref = new EmbeddedObjectReference(ContentType2, Description, FileName, Name,
                                                                                  ContentId, EmbeddedObjectId, Size);

                        if (E.LocalName == "inline")
                        {
                            if (Inline is null)
                            {
                                Inline = new List <EmbeddedObjectReference>();
                            }

                            Inline.Add(Ref);
                        }
                        else
                        {
                            if (Attachments is null)
                            {
                                Attachments = new List <EmbeddedObjectReference>();
                            }

                            Attachments.Add(Ref);
                        }
                        break;
                    }
                }
            }

            string PlainText = e.Body;
            string Html      = null;
            string Markdown  = null;

            foreach (XmlNode N in e.Message.ChildNodes)
            {
                if (N is XmlElement E)
                {
                    switch (E.LocalName)
                    {
                    case "content":
                        if (E.NamespaceURI == "urn:xmpp:content")
                        {
                            switch (XML.Attribute(E, "type").ToLower())
                            {
                            case "text/plain":
                                PlainText = E.InnerText;
                                break;

                            case "text/html":
                                Html = E.InnerText;
                                break;

                            case "text/markdown":
                                Markdown = E.InnerText;
                                break;
                            }
                        }
                        break;

                    case "html":
                        if (E.NamespaceURI == "http://jabber.org/protocol/xhtml-im")
                        {
                            foreach (XmlNode N2 in E.ChildNodes)
                            {
                                if (N2 is XmlElement E2 && E2.LocalName == "body")
                                {
                                    Html = E2.OuterXml;                                                         // InnerXml introduces xmlns attributes on all child elements.

                                    int i = Html.IndexOf('>');
                                    Html = Html.Substring(i + 1);

                                    i    = Html.LastIndexOf('<');
                                    Html = Html.Substring(0, i);
                                    break;
                                }
                            }
                        }
                        break;
                    }
                }
            }

            MailEventHandler h = this.MailReceived;

            if (!(h is null))
            {
                try
                {
                    await h(this, new MailEventArgs(this, e, ContentType, MessageId, (Mail.Priority)Priority,
                                                    Date, FromMail, FromHeader, Sender2, Size, MailObjectId, Headers.ToArray(), Attachments?.ToArray(),
                                                    Inline?.ToArray(), PlainText, Html, Markdown));
                }
                catch (Exception ex)
                {
                    Log.Critical(ex);
                }
            }
        }
Beispiel #5
0
        public void LoadAttachments(IEnumerable <MimePart> mimeParts, bool skipText)
        {
            if (Attachments == null)
            {
                Attachments = new List <MailAttachment>();
            }

            foreach (var mimePart in mimeParts)
            {
                if (skipText && mimePart.ContentType.Type.Contains("text"))
                {
                    continue;
                }

                if (mimePart.BinaryContent == null || mimePart.BinaryContent.Length == 0)
                {
                    continue;
                }

                var ext = Path.GetExtension(mimePart.Filename);

                if (string.IsNullOrEmpty(ext))
                {
                    // If the file extension is not specified, there will be issues with saving on s3
                    var newExt = ".ext";

                    if (mimePart.ContentType.Type.ToLower().IndexOf("image", StringComparison.Ordinal) != -1)
                    {
                        var subType = mimePart.ContentType.SubType;

                        newExt = ".png";

                        if (!string.IsNullOrEmpty(subType))
                        {
                            // List was get from http://en.wikipedia.org/wiki/Internet_media_type
                            var knownImageTypes = new List <string> {
                                "gif", "jpeg", "pjpeg", "png", "svg", "tiff", "ico", "bmp"
                            };

                            var foundExt = knownImageTypes
                                           .Find(s => subType.IndexOf(s, StringComparison.Ordinal) != -1);

                            if (!string.IsNullOrEmpty(foundExt))
                            {
                                newExt = "." + foundExt;
                            }
                        }
                    }
                    mimePart.Filename = Path.ChangeExtension(mimePart.Filename, newExt);
                }

                Attachments.Add(new MailAttachment
                {
                    contentId       = mimePart.EmbeddedObjectContentId,
                    size            = mimePart.Size,
                    fileName        = mimePart.Filename,
                    contentType     = mimePart.ContentType.MimeType,
                    data            = mimePart.BinaryContent,
                    contentLocation = mimePart.ContentLocation
                });
            }
        }
Beispiel #6
0
 /// <summary>
 /// Adds an attachment to the email.
 /// </summary>
 /// <param name="attachment">The attachment to add.</param>
 public void Attach(Attachment attachment)
 {
     Attachments.Add(attachment);
 }
Beispiel #7
0
        public void Attach(string target, EventCallback callback)
        {
            Logger.Debug($"[Events] Attaching callback to `{target}`");

            Attachments.Add(new EventAttachment(target, callback));
        }
Beispiel #8
0
 private void AddToAttachments(string fileName, byte[] bytes)
 {
     Attachments.Add(new Attachment(new MemoryStream(bytes), fileName));
 }
 /// <summary>
 /// Add attachment to the post. Attachments will be returned in the same order as added.
 /// </summary>
 /// <param name="attachment">media attachment.</param>
 /// <returns>same instance for a method chaining.</returns>
 public ActivityContent AddMediaAttachment(MediaAttachment attachment)
 {
     Attachments.Add(attachment);
     return(this);
 }
Beispiel #10
0
        public void AttachObject(ObjectGroup grp, AttachmentPoint attachpoint)
        {
            SceneInterface scene = grp.Scene;

            if (IsInScene(scene))
            {
                if (!scene.CanTake(this, grp, grp.Position))
                {
                    return;
                }

                bool change_permissions = false;
                UUID assetID;

                if (change_permissions)
                {
                    assetID = grp.NextOwnerAssetID;
                    if (UUID.Zero == assetID)
                    {
                        AssetData asset = grp.Asset(XmlSerializationOptions.WriteOwnerInfo | XmlSerializationOptions.WriteXml2 | XmlSerializationOptions.AdjustForNextOwner);
                        asset.ID = UUID.Random;
                        AssetService.Store(asset);
                        assetID = asset.ID;
                        AssetService.Store(asset);
                    }
                }
                else
                {
                    assetID = grp.OriginalAssetID;
                    if (UUID.Zero == assetID)
                    {
                        AssetData asset = grp.Asset(XmlSerializationOptions.WriteOwnerInfo | XmlSerializationOptions.WriteXml2);
                        asset.ID = UUID.Random;
                        AssetService.Store(asset);
                        assetID = asset.ID;
                        AssetService.Store(asset);
                    }
                }

                var newitem = new InventoryItem
                {
                    AssetID       = assetID,
                    AssetType     = AssetType.Object,
                    InventoryType = InventoryType.Object,
                    Name          = grp.Name,
                    Description   = grp.Description,
                    LastOwner     = grp.Owner,
                    Owner         = Owner,
                    Creator       = grp.RootPart.Creator,
                    CreationDate  = grp.RootPart.CreationDate
                };
                newitem.Permissions.Base     &= change_permissions ? grp.RootPart.NextOwnerMask : grp.RootPart.BaseMask;
                newitem.Permissions.Current   = newitem.Permissions.Base;
                newitem.Permissions.Group     = InventoryPermissionsMask.None;
                newitem.Permissions.NextOwner = grp.RootPart.NextOwnerMask;
                newitem.Permissions.EveryOne  = InventoryPermissionsMask.None;

                var attachAt = attachpoint & AttachmentPoint.PositionMask;
                if (attachAt != AttachmentPoint.Default && attachAt != grp.AttachPoint)
                {
                    grp.AttachedPos = Vector3.Zero;
                    grp.AttachedRot = Quaternion.Identity;
                }

                if (attachAt == AttachmentPoint.Default)
                {
                    attachAt = grp.AttachPoint;

                    if (attachAt == AttachmentPoint.NotAttached)
                    {
                        grp.AttachPoint = AttachmentPoint.LeftHand;
                        grp.AttachedPos = Vector3.Zero;
                        grp.AttachedRot = Quaternion.Identity;
                    }
                }

                ApplyNextOwner(grp, Owner);

                grp.IsAttached = true;
                grp.Position   = grp.AttachedPos;
                grp.Rotation   = grp.AttachedRot;

                Attachments.Add(grp.AttachPoint, grp);
                grp.PostEvent(new AttachEvent {
                    ObjectID = Owner.ID
                });
            }
        }
        private void AttachFromInventory(AssetData data, UUID itemID)
        {
            List <ObjectGroup> objgroups;

#if DEBUG
            m_Log.DebugFormat("Deserializing object asset {0} for agent {1} {2} ({3})", data.ID, NamedOwner.FirstName, NamedOwner.LastName, NamedOwner.ID);
#endif
            try
            {
                objgroups = ObjectXML.FromAsset(data, Owner);
            }
            catch (Exception e)
            {
                m_Log.WarnFormat("Deserialization error for object asset {0} for agent {1} {2} ({3}): {4}: {5}",
                                 data.ID, NamedOwner.FirstName, NamedOwner.LastName, NamedOwner.ID, e.GetType().FullName, e.ToString());
                return;
            }

            if (objgroups.Count != 1)
            {
                return;
            }

            ObjectGroup grp = objgroups[0];

            foreach (ObjectPart part in grp.Values)
            {
                if (part.Shape.PCode == PrimitiveCode.Grass ||
                    part.Shape.PCode == PrimitiveCode.Tree ||
                    part.Shape.PCode == PrimitiveCode.NewTree)
                {
                    return;
                }
            }

            AttachmentPoint attachAt = grp.AttachPoint;

            if (attachAt == AttachmentPoint.NotAttached)
            {
                grp.AttachPoint = AttachmentPoint.LeftHand;
                grp.AttachedPos = Vector3.Zero;
                grp.AttachedRot = Quaternion.Identity;
            }

            grp.FromItemID       = itemID;
            grp.IsAttached       = true;
            grp.Position         = grp.AttachedPos;
            grp.Rotation         = grp.AttachedRot;
            grp.IsChangedEnabled = true;

#if DEBUG
            m_Log.DebugFormat("Adding attachment asset {0} at {4} for agent {1} {2} ({3})", data.ID, NamedOwner.FirstName, NamedOwner.LastName, NamedOwner.ID, grp.AttachPoint.ToString());
#endif
            SceneInterface scene = CurrentScene;
            try
            {
                scene.Add(grp);
                Attachments.Add(grp.AttachPoint, grp);
            }
            catch
            {
                return;
            }
        }
		private void AddAttachmentToMsg(Attachment attachment, Attachments attachments, int index, bool isAnEmbeddedEmail)
		{
			string fileName = attachment.FileName;

			if (isAnEmbeddedEmail)
			{
				// A subject line like 
				// "test messed up subject line, invalid characters: /\/\ 29/04/2004\"
				// in an email is why LocalCopyOfFileManager.GetValidFileName() cant be used
				//
				// Change to replace invalid characters by underscore to avoid potential empty file name. e.g. '   .msg'

				// we need .msg extension to use Namespace.OpenSharedItem()
				if (!File.Exists(Path.ChangeExtension(fileName, MsgExtension)))
				{
					fileName = Path.ChangeExtension(fileName, MsgExtension);
					File.Copy(attachment.FileName, fileName);
				}
				_msgFileBackingCopies.Add(fileName);

                dynamic nameSpace = OutlookApp.GetNamespace("MAPI");
                var mitem = nameSpace.OpenSharedItem(fileName);
                using (new ComRelease(mitem))
                {
                    var mailItem = attachments.Parent;
                    using (new ComRelease(mailItem))
                    {
						if (mailItem != null && (Microsoft.Office.Interop.Outlook.OlBodyFormat)mailItem.BodyFormat != OlBodyFormat.olFormatRichText)
                        {
                            index = 1;
                        }
                        var newAttach = attachments.Add(mitem, OlAttachmentType.olEmbeddeditem, index,
													  attachment.Name);
                        using (new ComRelease(newAttach))
                        {
                            var propertyAccessor = newAttach.PropertyAccessor;
                            using (new ComRelease(propertyAccessor))
                            {
                                string displayname = mitem.Subject;
                                if (string.IsNullOrEmpty(displayname) || string.IsNullOrEmpty(displayname.Trim()))
                                {
                                    propertyAccessor.SetProperty(MAPIStringDefines.PR_DISPLAY_NAME_W,
                                                                            UntitledAttachmentTitle);
                                }
                                else
                                {
                                    propertyAccessor.SetProperty(MAPIStringDefines.PR_DISPLAY_NAME_W,
                                                                            mitem.Subject);
                                }
                            }
                        }
                    }
                }

			    // need to do this to ensure mitem does not hold onto file used to create it
				GC.Collect();
				GC.WaitForPendingFinalizers();
				///////////////////////////////////////////////////////////////////////////////	
			}
			else
			{
				if (!attachment.IsSignature)
				{
					var mailItem = attachments.Parent;
					if (mailItem != null && (Microsoft.Office.Interop.Outlook.OlBodyFormat)mailItem.BodyFormat != OlBodyFormat.olFormatRichText)
					{
						index = 1;
					}
					attachments.Add(fileName, OlAttachmentType.olByValue, index, attachment.Name);
				}
			}
		}
		private void ZipAttachments(Attachments attachments, IEnumerable<Attachment> processedAttachments, ZipAllOptions zipAll, OlBodyFormat bodyFormat)
		{
			IFile zipfile;
			const string groupName = "attachments.zip";
			string filename = string.Empty;
			string attachName = string.Empty;
			string tempDir = string.Empty;

			try
			{
				RemoveAllAttachmentsFromMsg(attachments, bodyFormat);
				const int iRenderingPosition = 1;
				zipfile = FileFactory.Create(groupName, FileType.ZIP);

				foreach (Attachment attachment in processedAttachments)
				{
					if (!attachment.IsSignature)
					{
						IFile attachmentFile = FileFactory.Create(attachment.FileName, attachment.Name);
						zipfile.Add(attachmentFile);
					}
				}
				SetEncryption(zipfile, zipAll);
				zipfile.PackContainer(zipAll.PassWord);
				tempDir = FileToDisk(zipfile.FileName, zipfile);
				attachName = Path.Combine(tempDir, zipfile.FileName);
				Microsoft.Office.Interop.Outlook.Attachment newAttachment = attachments.Add(attachName, OlAttachmentType.olByValue, iRenderingPosition, zipfile.DisplayName);

				Encoding ansiEncoding = Encoding.GetEncoding(Encoding.Default.CodePage, new EncoderExceptionFallback(), new DecoderExceptionFallback());
				try
				{
					byte[] ansiBytes = ansiEncoding.GetBytes(zipfile.FileName);
				}
				catch (EncoderFallbackException /*ex*/)
				{
					newAttachment.PropertyAccessor.SetProperty(MAPIStringDefines.PR_ATTACH_LONG_FILENAME_W, zipfile.FileName);
					newAttachment.PropertyAccessor.SetProperty(MAPIStringDefines.PR_ATTACH_FILENAME_W, zipfile.FileName);
					newAttachment.PropertyAccessor.SetProperty(MAPIStringDefines.PR_DISPLAY_NAME_W, zipfile.DisplayName);
				}
			}
			catch (Exception ex)
			{
				Interop.Logging.Logger.LogError(ex);
				throw;
			}
			finally
			{
				if (!string.IsNullOrEmpty(filename) && File.Exists(filename))
				{
					File.Delete(filename);
				}
				if (!string.IsNullOrEmpty(attachName) && File.Exists(attachName))
				{
					File.Delete(attachName);
				}
				if (!string.IsNullOrEmpty(tempDir) && Directory.Exists(tempDir))
				{
					Directory.Delete(tempDir);
				}
			}
		}
Beispiel #14
0
 public void AddAttachment(BusinessEntities.File file, bool specificVersion = true)
 {
     Attachments.Add(new Attachment {
         File = file, SpecificVersion = true
     });
 }
Beispiel #15
0
 public void AddAttachment(IMessageAttachment attachment)
 {
     Attachments.Add(attachment);
 }
Beispiel #16
0
        internal void ParseMessageSection(String bound, String[] lines, ref int i)
        {
            for (; i < lines.Length; i++)
            {
                lines[i] = lines[i].TrimStart('\t');

                if (lines[i] == "--" + bound + "--")
                {
                    return;                                  //its all over for this section
                }
                if (lines[i] == "--" + bound)
                {
                    //beginning of the section, start looking for headers
                    String currentType  = "text/plain";
                    String newBound     = "";
                    String filename     = "";
                    bool   isAttachment = false;

                    while (lines[i] != "")
                    {
                        var currentLine = lines[i];

                        while (lines[i + 1].StartsWith("\t") || lines[i + 1].StartsWith(" "))
                        {
                            currentLine = currentLine.Trim() + " " + lines[++i].Trim();
                        }

                        if (currentLine.StartsWith("Content-Type") || currentLine.StartsWith("boundary"))
                        {
                            String[] parts = currentLine.Split(':');
                            String[] bits  = parts[1].Split(';');
                            currentType = bits[0].Trim();

                            for (int x = 0; x < bits.Length; x++)
                            {
                                bits[x] = bits[x].Trim();
                                if (bits[x].StartsWith("boundary=\""))
                                {
                                    newBound = bits[x].Substring(10, bits[x].Length - 11);
                                }
                                else if (bits[x].StartsWith("boundary"))
                                {
                                    newBound = bits[x].Substring(9, bits[x].Length - 9);
                                }
                            }
                        }
                        else if (currentLine.StartsWith("Content-Disposition"))
                        {
                            String[] m_parts = lines[i].Split(':');
                            String[] m_bits  = m_parts[1].Split(';');
                            isAttachment = m_bits[0].Trim() == "attachment" ? true : false;

                            for (int x = 0; x < m_bits.Length; x++)
                            {
                                m_bits[x] = m_bits[x].Trim();
                                if (m_bits[x].StartsWith("filename=\""))
                                {
                                    filename = m_bits[x].Substring(10, m_bits[x].Length - 11);
                                }
                                else if (m_bits[x].StartsWith("filename="))
                                {
                                    filename = m_bits[x].Substring(9, m_bits[x].Length - 9);
                                }
                            }
                        }

                        i++;
                    }

                    if (newBound != "")
                    {
                        //check for new section
                        ParseMessageSection(newBound, lines, ref i);
                    }

                    if (MimeTypeHandler == null || MimeTypeHandler(currentType, lines, ref i, this) == false)
                    {
                        StringBuilder m_bld = new StringBuilder();

                        for (; i < lines.Length; i++)
                        {
                            if (lines[i] == "--" + bound)
                            {
                                break;
                            }
                            if (lines[i] == "--" + bound + "--")
                            {
                                break;
                            }
                            if (isAttachment)
                            {
                                m_bld.Append(lines[i]);
                            }
                            else
                            {
                                m_bld.AppendLine(lines[i]);
                            }
                        }

                        i--;
                        if (isAttachment)
                        {
                            var attachment = new Pop3Attachment
                            {
                                Name = filename,
                                Type = currentType,
                                Data = Convert.FromBase64String(m_bld.ToString())
                            };

                            //add to attachment list
                            Attachments.Add(attachment);
                        }
                        else if (currentType == "text/plain")
                        {
                            this.BodyText = m_bld.ToString();
                        }
                        else if (currentType == "text/html")
                        {
                            this.BodyHtml = m_bld.ToString();
                        }
                    }
                }
            }
        }
Beispiel #17
0
 public void AddAttachment(string fileName, byte[] content, string mimeType)
 {
     Attachments.Add(new Attachment(new MemoryStream(content), fileName, mimeType));
 }
Beispiel #18
0
        public override void ParsePayload(string payload)
        {
            if (payload == null)
            {
                return;
            }

            Dictionary <string, string> dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(payload);

            foreach (var kv in dict)
            {
                if (string.IsNullOrWhiteSpace(kv.Value))
                {
                    continue;
                }

                string key   = kv.Key;
                string value = kv.Value;

                switch (key)
                {
                case "ToAddresses":
                    AddEmailsToList(value, ToAddresses);
                    break;

                case "CcAddresses":
                    AddEmailsToList(value, CcAddresses);
                    break;

                case "BccAddresses":
                    AddEmailsToList(value, BccAddresses);
                    break;

                case "Subject":
                    Subject = value;
                    break;

                case "Body":
                    Body = value;
                    break;

                case "FromAddress":
                    FromAddress = value;
                    break;

                case "FromDisplayName":
                    FromDisplayName = value;
                    break;

                case "FormatAsHtml":
                    FormatAsHtml = value == "True";
                    break;

                case "MailPriority":
                    Priority = (MailPriority)Convert.ToInt32(value);
                    break;

                case "Attachments":
                    string[] attArr = value.Split(new string[] { ATTACHMENTBOUNDARY }, StringSplitOptions.RemoveEmptyEntries);
                    if (attArr != null && attArr.Length > 1)
                    {
                        string[] fnArr = attArr[0].Split('|');

                        for (int i = 0; i < fnArr.Length; i++)
                        {
                            string fn      = UnescapeString(fnArr[i]);
                            string byteStr = attArr[i + 1];

                            if (!string.IsNullOrWhiteSpace(byteStr))
                            {
                                Attachments.Add(fn, Convert.FromBase64String(byteStr));
                            }
                        }
                    }
                    break;

                case "SendCcToSystemEmail":
                    SendCcToSystemEmail = value == "True";
                    break;
                }
            }
        }
Beispiel #19
0
 private void AddAttachmentCommand(object obj)
 {
     AttachmentCount++;
     Attachments.Add($"Anexo nº: {AttachmentCount}");
 }
        private void ParseMessageSection(String bound, String[] lines, ref int i)
        {
            for (; i < lines.Length; i++)
            {
                if (lines[i] == "--" + bound + "--")
                {
                    return;                                                  //its all over for this section
                }
                if (lines[i] != "--" + bound)
                {
                    continue;
                }

                //beginning of the section, start looking for headers
                String currentType       = "text/plain";
                String newBound          = "";
                String filename          = "";
                String transportEncoding = "plain";
                bool   isAttachment      = false;

                while (lines[i] != "")
                {
                    if (lines[i].StartsWith("Content-Type"))
                    {
                        String[] parts = lines[i].Split(':');
                        String[] bits  = parts[1].Split(';');
                        currentType = bits[0].Trim();

                        for (int x = 0; x < bits.Length; x++)
                        {
                            bits[x] = bits[x].Trim();
                            if (bits[x].StartsWith("boundary=\""))
                            {
                                newBound = bits[x].Substring(10, bits[x].Length - 11);
                            }
                            else if (bits[x].StartsWith("boundary"))
                            {
                                newBound = bits[x].Substring(9, bits[x].Length - 9);
                            }
                        }
                    }
                    else if (lines[i].StartsWith("Content-Disposition"))
                    {
                        String[] parts = lines[i].Split(':');
                        String[] bits  = parts[1].Split(';');
                        isAttachment = bits[0].Trim() == "attachment";

                        for (int x = 0; x < bits.Length; x++)
                        {
                            bits[x] = bits[x].Trim();
                            if (bits[x].StartsWith("filename=\""))
                            {
                                filename = bits[x].Substring(10, bits[x].Length - 11);
                            }
                            else if (bits[x].StartsWith("filename="))
                            {
                                filename = bits[x].Substring(9, bits[x].Length - 9);
                            }
                        }
                    }
                    else if (lines[i].StartsWith("Content-Transfer-Encoding"))
                    {
                        transportEncoding = lines[i].Substring(27);
                    }

                    i++;
                }

                if (newBound != "")
                {
                    //check for new section
                    ParseMessageSection(newBound, lines, ref i);
                }

                if (MimeTypeHandler != null && MimeTypeHandler(currentType, lines, ref i, this))
                {
                    continue;
                }

                StringBuilder messageBuilder = new StringBuilder();

                for (; i < lines.Length; i++)
                {
                    if (lines[i] == "--" + bound)
                    {
                        break;
                    }
                    if (lines[i] == "--" + bound + "--")
                    {
                        break;
                    }
                    if (isAttachment)
                    {
                        messageBuilder.Append(lines[i]);
                    }
                    else
                    {
                        messageBuilder.AppendLine(lines[i]);
                    }
                }

                i--;
                if (isAttachment)
                {
                    Imap4Attachment currentAttachment = new Imap4Attachment
                    {
                        Name = filename,
                        Type = currentType,
                        Data = Convert.FromBase64String(messageBuilder.ToString())
                    };

                    //add to attachment list
                    Attachments.Add(currentAttachment);
                }
                else
                {
                    switch (currentType)
                    {
                    case "text/plain":
                        BodyText = messageBuilder.ToString().Trim();
                        break;

                    case "text/html":
                        BodyHtml = messageBuilder.ToString().Trim();
                        if (transportEncoding == "base64")
                        {
                            BodyHtml = Encoding.ASCII.GetString(Convert.FromBase64String(BodyHtml));
                        }
                        break;
                    }
                }
            }
        }
Beispiel #21
0
        public EmailMessage(string recipients, string subject, string body, string[] files)
        {
            From = new MailAddress(Parameters.FROM, App.Name, Encoding.UTF8);

            To.Add(recipients.Replace(';', ','));
            // this.CC
            // this.Bcc
            // this.ReplyToList;

            // this.IsBodyHtml = true;
            // this.Priority = MailPriority.High;

            string mode = Parameters.MODE;

            if (subject.Length > 0)
            {
                int m = mode.IndexOf(subject[0]);
                if (m > -1)
                {
                    Subject = SubjBuilder(m, subject);
                }
                else
                {
                    Subject = subject;
                }
            }

            if (body.Length > 0)
            {
                if (mode.IndexOf(body[0]) > -1)
                {
                    string   list     = Parameters.LIST;
                    string[] bodyList = body.Split(list.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    foreach (string item in bodyList)
                    {
                        int m = mode.IndexOf(item[0]);
                        if (m > -1)
                        {
                            Body += BodyBuilder(m, item);
                        }
                    }
                }
                else
                {
                    Body = body;
                }
            }

            foreach (string file in files)
            {
                FileInfo fi = new FileInfo(file.Trim());
                if (fi.Exists)
                {
                    Attachment         attachment  = new Attachment(fi.FullName);
                    ContentDisposition disposition = attachment.ContentDisposition;

                    disposition.CreationDate     = fi.CreationTime;
                    disposition.ModificationDate = fi.LastWriteTime;
                    disposition.ReadDate         = fi.LastAccessTime;

                    Attachments.Add(attachment);
                }
                else
                {
                    Trace.TraceWarning("Attachment file " + fi.FullName + " not found!");
                }
            }
        }
Beispiel #22
0
 public void AddAttachment(string filepath, bool deleteAfterSubmit = false) => Attachments.Add(new JiraAttachment(filepath, deleteAfterSubmit));
        /// <summary>
        /// 加载配置文件
        /// </summary>
        /// <returns></returns>
        private bool LoadConfig()
        {
            string configPath = ViewModel.ConfigFilePath;

            if (File.Exists(configPath))
            {
                try
                {
                    MainConfigModel = new MainConfigModel
                    {
                        FilePath              = IniFileReadUtil.ReadIniData("Main", "FilePath", null, configPath),
                        SuccessSimple         = IniFileReadUtil.ReadIniData("Main", "SuccessSimple", null, configPath),
                        SuccessSimpleLocation = IniFileReadUtil.ReadIniData("Main", "SuccessSimpleLocation", null, configPath),
                        SheetNames            = IniFileReadUtil.ReadIniData("Main", "SheetNames", null, configPath).Split(',').ToList(),
                        MainSheetName         = IniFileReadUtil.ReadIniData("Main", "MainSheetName", null, configPath),
                        TemplatePath          = IniFileReadUtil.ReadIniData("Main", "TemplatePath", null, configPath),
                        BodyParamCount        = int.Parse(IniFileReadUtil.ReadIniData("Main", "BodyParamCount", null, configPath)),
                        SubjectParamCount     = int.Parse(IniFileReadUtil.ReadIniData("Main", "SubjectParamCount", null, configPath)),
                        MailToParamCount      = int.Parse(IniFileReadUtil.ReadIniData("Main", "MailToParamCount", null, configPath)),
                        AttachmentCount       = int.Parse(IniFileReadUtil.ReadIniData("Main", "AttachmentCount", null, configPath)),
                    };
                    MailConfigModel = new MailConfigModel
                    {
                        MailTo       = IniFileReadUtil.ReadIniData("Mail", "MailTo", null, configPath),
                        MailAddress  = IniFileReadUtil.ReadIniData("Mail", "MailAddress", null, configPath),
                        MailPassword = IniFileReadUtil.ReadIniData("Mail", "MailPassword", null, configPath),
                        MailSubject  = IniFileReadUtil.ReadIniData("Mail", "MailSubject", null, configPath),
                        SMTPAddress  = IniFileReadUtil.ReadIniData("Mail", "SMTPAddress", null, configPath),
                        Port         = int.Parse(IniFileReadUtil.ReadIniData("Mail", "Port", null, configPath)),
                        EnableSsl    = bool.Parse(IniFileReadUtil.ReadIniData("Mail", "EnableSsl", null, configPath)),
                        Priority     = int.Parse(IniFileReadUtil.ReadIniData("Mail", "Priority", null, configPath)),
                    };
                    foreach (var sheetName in MainConfigModel.SheetNames)
                    {
                        SheetConfigModel sheetConfigModel = new SheetConfigModel
                        {
                            StartingLine           = int.Parse(IniFileReadUtil.ReadIniData(sheetName, "StartingLine", null, configPath)),
                            EndLine                = int.Parse(IniFileReadUtil.ReadIniData(sheetName, "EndLine", null, configPath)),
                            UniquelyIdentifiesLine = IniFileReadUtil.ReadIniData(sheetName, "UniquelyIdentifiesLine", null, configPath),
                        };
                        SheetConfigModels[sheetName] = sheetConfigModel;
                    }
                    for (int i = 0; i < MainConfigModel.BodyParamCount; i++)
                    {
                        BodyParams.Add(IniFileReadUtil.ReadIniData("BodyParams", i.ToString(), null, configPath));
                    }
                    for (int i = 0; i < MainConfigModel.SubjectParamCount; i++)
                    {
                        SubjectParams.Add(IniFileReadUtil.ReadIniData("SubjectParams", i.ToString(), null, configPath));
                    }
                    for (int i = 0; i < MainConfigModel.MailToParamCount; i++)
                    {
                        MailToParams.Add(IniFileReadUtil.ReadIniData("MailToParams", i.ToString(), null, configPath));
                    }
                    for (int i = 0; i < MainConfigModel.AttachmentCount; i++)
                    {
                        Attachments.Add(IniFileReadUtil.ReadIniData("Attachments", i.ToString(), null, configPath));
                    }
                    //加载工作簿相关内容
                    Workbook = LoadWorkbook(MainConfigModel.FilePath);
                    foreach (var sheetName in MainConfigModel.SheetNames)
                    {
                        SheetName2ExcelSheet[sheetName] = LoadWorksheet(Workbook, sheetName);
                    }
                    PushMessage("读取成功。\n");
                    return(true);
                }
                catch (Exception ex)
                {
                    PushMessage("读取失败。\n");
                    PushMessage(ex.Message + "\n");
                    return(false);
                }
            }
            else
            {
                PushMessage("找不到配置文件!\n");
                return(false);
            }
        }
Beispiel #24
0
        /// <summary>
        /// Initializes a populated instance of the OpaqueMail.ReadOnlyMailMessage class representing the message text passed in with attachments procesed according to the attachment filter flags.
        /// </summary>
        /// <param name="messageText">The raw contents of the e-mail message.</param>
        /// <param name="processingFlags">Flags determining whether specialized properties are returned with a ReadOnlyMailMessage.</param>
        /// <param name="parseExtendedHeaders">Whether to populate the ExtendedHeaders object.</param>
        public ReadOnlyMailMessage(string messageText, ReadOnlyMailMessageProcessingFlags processingFlags, bool parseExtendedHeaders)
        {
            if (((processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeRawHeaders) > 0) &&
                (processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeRawBody) > 0)
            {
                RawMessage = messageText;
            }

            // Remember which specialized attachments to include.
            ProcessingFlags = processingFlags;

            // Fix messages whose carriage returns have been stripped.
            if (messageText.IndexOf("\r") < 0)
            {
                messageText = messageText.Replace("\n", "\r\n");
            }

            // Separate the headers for processing.
            string headers;
            int    cutoff = messageText.IndexOf("\r\n\r\n");

            if (cutoff > -1)
            {
                headers = messageText.Substring(0, cutoff);
            }
            else
            {
                headers = messageText;
            }

            // Set the raw headers property if requested.
            if ((processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeRawHeaders) > 0)
            {
                RawHeaders = headers;
            }

            // Calculate the size of the message.
            Size = messageText.Length;

            // Temporary header variables to be processed by Functions.FromMailAddressString() later.
            string fromText    = "";
            string toText      = "";
            string ccText      = "";
            string bccText     = "";
            string replyToText = "";
            string subjectText = "";

            // Temporary header variables to be processed later.
            List <string> receivedChain = new List <string>();
            string        receivedText  = "";

            // Unfold any unneeded whitespace, then loop through each line of the headers.
            string[] headersList = Functions.UnfoldWhitespace(headers).Replace("\r", "").Split('\n');
            foreach (string header in headersList)
            {
                // Split header {name:value} pairs by the first colon found.
                int colonPos = header.IndexOf(":");
                if (colonPos > -1 && colonPos < header.Length - 1)
                {
                    string[] headerParts = new string[] { header.Substring(0, colonPos), header.Substring(colonPos + 1).TrimStart(new char[] { ' ' }) };
                    string   headerType  = headerParts[0].ToLower();
                    string   headerValue = headerParts[1];

                    // Set header variables for common headers.
                    if (!string.IsNullOrEmpty(headerType) && !string.IsNullOrEmpty(headerValue))
                    {
                        Headers[headerParts[0]] = headerValue;
                    }

                    switch (headerType)
                    {
                    case "cc":
                        if (ccText.Length > 0)
                        {
                            ccText += ", ";
                        }
                        ccText = headerValue;
                        break;

                    case "content-transfer-encoding":
                        ContentTransferEncoding = headerValue;
                        switch (headerValue.ToLower())
                        {
                        case "base64":
                            BodyTransferEncoding = TransferEncoding.Base64;
                            break;

                        case "quoted-printable":
                            BodyTransferEncoding = TransferEncoding.QuotedPrintable;
                            break;

                        case "7bit":
                            BodyTransferEncoding = TransferEncoding.SevenBit;
                            break;

                        case "8bit":
                            BodyTransferEncoding = TransferEncoding.EightBit;
                            break;

                        default:
                            BodyTransferEncoding = TransferEncoding.Unknown;
                            break;
                        }
                        break;

                    case "content-language":
                        ContentLanguage = headerValue;
                        break;

                    case "content-type":
                        // If multiple content-types are passed, only process the first.
                        if (string.IsNullOrEmpty(ContentType))
                        {
                            ContentType = headerValue.Trim();
                            CharSet     = Functions.ExtractMimeParameter(ContentType, "charset");
                        }
                        break;

                    case "date":
                        string dateString = headerValue;

                        // Ignore extraneous datetime information.
                        int dateStringParenthesis = dateString.IndexOf("(");
                        if (dateStringParenthesis > -1)
                        {
                            dateString = dateString.Substring(0, dateStringParenthesis - 1);
                        }

                        // Remove timezone suffix.
                        if (dateString.Substring(dateString.Length - 4, 1) == " ")
                        {
                            dateString = dateString.Substring(0, dateString.Length - 4);
                        }

                        DateTime.TryParse(dateString, out Date);
                        break;

                    case "delivered-to":
                        DeliveredTo = headerValue;
                        break;

                    case "from":
                        fromText = headerValue;
                        break;

                    case "importance":
                        Importance = headerValue;
                        break;

                    case "in-reply-to":
                        // Ignore opening and closing <> characters.
                        InReplyTo = headerValue;
                        if (InReplyTo.StartsWith("<"))
                        {
                            InReplyTo = InReplyTo.Substring(1);
                        }
                        if (InReplyTo.EndsWith(">"))
                        {
                            InReplyTo = InReplyTo.Substring(0, InReplyTo.Length - 1);
                        }
                        break;

                    case "message-id":
                        // Ignore opening and closing <> characters.
                        MessageId = headerValue;
                        if (MessageId.StartsWith("<"))
                        {
                            MessageId = MessageId.Substring(1);
                        }
                        if (MessageId.EndsWith(">"))
                        {
                            MessageId = MessageId.Substring(0, MessageId.Length - 1);
                        }
                        break;

                    case "received":
                    case "x-received":
                        if (!string.IsNullOrEmpty(receivedText))
                        {
                            receivedChain.Add(receivedText);
                        }

                        receivedText = headerValue;
                        break;

                    case "replyto":
                    case "reply-to":
                        replyToText = headerValue;
                        break;

                    case "return-path":
                        // Ignore opening and closing <> characters.
                        ReturnPath = headerValue;
                        if (ReturnPath.StartsWith("<"))
                        {
                            ReturnPath = ReturnPath.Substring(1);
                        }
                        if (ReturnPath.EndsWith(">"))
                        {
                            ReturnPath = ReturnPath.Substring(0, ReturnPath.Length - 1);
                        }
                        break;

                    case "sender":
                    case "x-sender":
                        if (headerValue.Length > 0)
                        {
                            MailAddressCollection senderCollection = Functions.FromMailAddressString(headerValue);
                            if (senderCollection.Count > 0)
                            {
                                this.Sender = senderCollection[0];
                            }
                        }
                        break;

                    case "subject":
                        subjectText = headerValue;
                        break;

                    case "to":
                        if (toText.Length > 0)
                        {
                            toText += ", ";
                        }
                        toText += headerValue;
                        break;

                    case "x-priority":
                        switch (headerValue.ToUpper())
                        {
                        case "LOW":
                            Priority = MailPriority.Low;
                            break;

                        case "NORMAL":
                            Priority = MailPriority.Normal;
                            break;

                        case "HIGH":
                            Priority = MailPriority.High;
                            break;
                        }
                        break;

                    case "x-subject-encryption":
                        bool.TryParse(headerValue, out SubjectEncryption);
                        break;

                    default:
                        break;
                    }

                    // Set header variables for advanced headers.
                    if (parseExtendedHeaders)
                    {
                        ExtendedProperties = new ExtendedProperties();

                        switch (headerType)
                        {
                        case "acceptlanguage":
                        case "accept-language":
                            ExtendedProperties.AcceptLanguage = headerValue;
                            break;

                        case "authentication-results":
                            ExtendedProperties.AuthenticationResults = headerValue;
                            break;

                        case "bounces-to":
                        case "bounces_to":
                            ExtendedProperties.BouncesTo = headerValue;
                            break;

                        case "content-description":
                            ExtendedProperties.ContentDescription = headerValue;
                            break;

                        case "dispositionnotificationto":
                        case "disposition-notification-to":
                            ExtendedProperties.DispositionNotificationTo = headerValue;
                            break;

                        case "dkim-signature":
                        case "domainkey-signature":
                        case "x-google-dkim-signature":
                            ExtendedProperties.DomainKeySignature = headerValue;
                            break;

                        case "domainkey-status":
                            ExtendedProperties.DomainKeyStatus = headerValue;
                            break;

                        case "errors-to":
                            ExtendedProperties.ErrorsTo = headerValue;
                            break;

                        case "list-unsubscribe":
                        case "x-list-unsubscribe":
                            ExtendedProperties.ListUnsubscribe = headerValue;
                            break;

                        case "mailer":
                        case "x-mailer":
                            ExtendedProperties.Mailer = headerValue;
                            break;

                        case "organization":
                        case "x-originator-org":
                        case "x-originatororg":
                        case "x-organization":
                            ExtendedProperties.OriginatorOrg = headerValue;
                            break;

                        case "original-messageid":
                        case "x-original-messageid":
                            ExtendedProperties.OriginalMessageId = headerValue;
                            break;

                        case "originating-email":
                        case "x-originating-email":
                            ExtendedProperties.OriginatingEmail = headerValue;
                            break;

                        case "precedence":
                            ExtendedProperties.Precedence = headerValue;
                            break;

                        case "received-spf":
                            ExtendedProperties.ReceivedSPF = headerValue;
                            break;

                        case "references":
                            ExtendedProperties.References = headerValue;
                            break;

                        case "resent-date":
                            string dateString = headerValue;

                            // Ignore extraneous datetime information.
                            int dateStringParenthesis = dateString.IndexOf("(");
                            if (dateStringParenthesis > -1)
                            {
                                dateString = dateString.Substring(0, dateStringParenthesis - 1);
                            }

                            // Remove timezone suffix.
                            if (dateString.Substring(dateString.Length - 4) == " ")
                            {
                                dateString = dateString.Substring(0, dateString.Length - 4);
                            }

                            DateTime.TryParse(dateString, out ExtendedProperties.ResentDate);
                            break;

                        case "resent-from":
                            ExtendedProperties.ResentFrom = headerValue;
                            break;

                        case "resent-message-id":
                            ExtendedProperties.ResentMessageID = headerValue;
                            break;

                        case "thread-index":
                            ExtendedProperties.ThreadIndex = headerValue;
                            break;

                        case "thread-topic":
                            ExtendedProperties.ThreadTopic = headerValue;
                            break;

                        case "user-agent":
                        case "useragent":
                            ExtendedProperties.UserAgent = headerValue;
                            break;

                        case "x-auto-response-suppress":
                            ExtendedProperties.AutoResponseSuppress = headerValue;
                            break;

                        case "x-campaign":
                        case "x-campaign-id":
                        case "x-campaignid":
                        case "x-mllistcampaign":
                        case "x-rpcampaign":
                            ExtendedProperties.CampaignID = headerValue;
                            break;

                        case "x-delivery-context":
                            ExtendedProperties.DeliveryContext = headerValue;
                            break;

                        case "x-maillist-id":
                            ExtendedProperties.MailListId = headerValue;
                            break;

                        case "x-msmail-priority":
                            ExtendedProperties.MSMailPriority = headerValue;
                            break;

                        case "x-originalarrivaltime":
                        case "x-original-arrival-time":
                            dateString = headerValue;

                            // Ignore extraneous datetime information.
                            dateStringParenthesis = dateString.IndexOf("(");
                            if (dateStringParenthesis > -1)
                            {
                                dateString = dateString.Substring(0, dateStringParenthesis - 1);
                            }

                            // Remove timezone suffix.
                            if (dateString.Substring(dateString.Length - 4) == " ")
                            {
                                dateString = dateString.Substring(0, dateString.Length - 4);
                            }

                            DateTime.TryParse(dateString, out ExtendedProperties.OriginalArrivalTime);
                            break;

                        case "x-originating-ip":
                            ExtendedProperties.OriginatingIP = headerValue;
                            break;

                        case "x-rcpt-to":
                            if (headerValue.Length > 1)
                            {
                                ExtendedProperties.RcptTo = headerValue.Substring(1, headerValue.Length - 2);
                            }
                            break;

                        case "x-csa-complaints":
                        case "x-complaints-to":
                        case "x-reportabuse":
                        case "x-report-abuse":
                        case "x-mail_abuse_inquiries":
                            ExtendedProperties.ReportAbuse = headerValue;
                            break;

                        case "x-spam-score":
                            ExtendedProperties.SpamScore = headerValue;
                            break;

                        default:
                            break;
                        }
                    }
                }
            }

            // Track all Received and X-Received headers.
            if (!string.IsNullOrEmpty(receivedText))
            {
                receivedChain.Add(receivedText);
            }
            ReceivedChain = receivedChain.ToArray();

            // Process the body if it's passed in.
            string body = "";

            if (cutoff > -1)
            {
                body = messageText.Substring(cutoff + 2);
            }
            if (!string.IsNullOrEmpty(body))
            {
                // Set the raw body property if requested.
                if ((processingFlags & ReadOnlyMailMessageProcessingFlags.IncludeRawBody) > 0)
                {
                    RawBody = body;
                }

                // Parse body into MIME parts.
                List <MimePart> mimeParts = MimePart.ExtractMIMEParts(ContentType, CharSet, ContentTransferEncoding, body, ProcessingFlags);

                // Process each MIME part.
                if (mimeParts.Count > 0)
                {
                    // Keep track of S/MIME signing and envelope encryption.
                    bool allMimePartsSigned = true, allMimePartsEncrypted = true, allMimePartsTripleWrapped = true;

                    // Process each MIME part.
                    for (int j = 0; j < mimeParts.Count; j++)
                    {
                        MimePart mimePart = mimeParts[j];

                        int semicolon = mimePart.ContentType.IndexOf(";");
                        if (semicolon > -1)
                        {
                            string originalContentType = mimePart.ContentType;
                            mimePart.ContentType = mimePart.ContentType.Substring(0, semicolon);

                            if (mimePart.ContentType.ToUpper() == "MESSAGE/PARTIAL")
                            {
                                PartialMessageId = Functions.ExtractMimeParameter(originalContentType, "id");
                                int partialMessageNumber = 0;
                                if (int.TryParse(Functions.ExtractMimeParameter(originalContentType, "number"), out partialMessageNumber))
                                {
                                    PartialMessageNumber = partialMessageNumber;
                                }
                            }
                        }

                        // Extract any signing certificates.  If this MIME part isn't signed, the overall message isn't signed.
                        if (mimePart.SmimeSigned)
                        {
                            if (mimePart.SmimeSigningCertificates.Count > 0 && SmimeSigningCertificate == null)
                            {
                                foreach (X509Certificate2 signingCert in mimePart.SmimeSigningCertificates)
                                {
                                    if (!SmimeSigningCertificateChain.Contains(signingCert))
                                    {
                                        SmimeSigningCertificateChain.Add(signingCert);
                                        SmimeSigningCertificate = signingCert;
                                    }
                                }
                            }
                        }
                        else
                        {
                            allMimePartsSigned = false;
                        }

                        // If this MIME part isn't marked as being in an encrypted envelope, the overall message isn't encrypted.
                        if (!mimePart.SmimeEncryptedEnvelope)
                        {
                            // Ignore signatures and encryption blocks when determining if everything is encrypted.
                            if (!mimePart.ContentType.StartsWith("application/pkcs7-signature") && !mimePart.ContentType.StartsWith("application/x-pkcs7-signature") && !mimePart.ContentType.StartsWith("application/pkcs7-mime"))
                            {
                                allMimePartsEncrypted = false;
                            }
                        }

                        // If this MIME part isn't marked as being triple wrapped, the overall message isn't triple wrapped.
                        if (!mimePart.SmimeTripleWrapped)
                        {
                            // Ignore signatures and encryption blocks when determining if everything is triple wrapped.
                            if (!mimePart.ContentType.StartsWith("application/pkcs7-signature") && !mimePart.ContentType.StartsWith("application/x-pkcs7-signature") && !mimePart.ContentType.StartsWith("application/pkcs7-mime"))
                            {
                                allMimePartsTripleWrapped = false;
                            }
                        }

                        // Set the default primary body, defaulting to text/html and falling back to any text/*.
                        string contentTypeToUpper = mimePart.ContentType.ToUpper();
                        if (Body.Length < 1)
                        {
                            // If the MIME part is of type text/*, set it as the intial message body.
                            if (string.IsNullOrEmpty(mimePart.ContentType) || contentTypeToUpper.StartsWith("TEXT/"))
                            {
                                IsBodyHtml  = contentTypeToUpper.StartsWith("TEXT/HTML");
                                Body        = mimePart.Body;
                                CharSet     = mimePart.CharSet;
                                ContentType = mimePart.ContentType;
                                if (mimePart.ContentTransferEncoding != TransferEncoding.Unknown)
                                {
                                    BodyTransferEncoding = mimePart.ContentTransferEncoding;
                                }
                            }
                            else
                            {
                                // If the MIME part isn't of type text/*, treat is as an attachment.
                                MemoryStream attachmentStream = new MemoryStream(mimePart.BodyBytes);
                                Attachment   attachment;
                                if (mimePart.ContentType.IndexOf("/") > -1)
                                {
                                    attachment = new Attachment(attachmentStream, mimePart.Name, mimePart.ContentType);
                                }
                                else
                                {
                                    attachment = new Attachment(attachmentStream, mimePart.Name);
                                }

                                attachment.ContentId = mimePart.ContentID;
                                Attachments.Add(attachment);
                            }
                        }
                        else
                        {
                            // If the current body isn't text/html and this is, replace the default body with the current MIME part.
                            if (!ContentType.ToUpper().StartsWith("TEXT/HTML") && contentTypeToUpper.StartsWith("TEXT/HTML"))
                            {
                                // Add the previous default body as an alternate view.
                                MemoryStream  alternateViewStream = new MemoryStream(Encoding.UTF8.GetBytes(Body));
                                AlternateView alternateView       = new AlternateView(alternateViewStream, ContentType);
                                if (BodyTransferEncoding != TransferEncoding.Unknown)
                                {
                                    alternateView.TransferEncoding = BodyTransferEncoding;
                                }
                                AlternateViews.Add(alternateView);

                                IsBodyHtml  = true;
                                Body        = mimePart.Body;
                                CharSet     = mimePart.CharSet;
                                ContentType = mimePart.ContentType;
                                if (mimePart.ContentTransferEncoding != TransferEncoding.Unknown)
                                {
                                    BodyTransferEncoding = mimePart.ContentTransferEncoding;
                                }
                            }
                            else
                            {
                                // If the MIME part isn't of type text/*, treat is as an attachment.
                                MemoryStream attachmentStream = new MemoryStream(mimePart.BodyBytes);
                                Attachment   attachment;
                                if (mimePart.ContentType.IndexOf("/") > -1)
                                {
                                    attachment = new Attachment(attachmentStream, mimePart.Name, mimePart.ContentType);
                                }
                                else
                                {
                                    attachment = new Attachment(attachmentStream, mimePart.Name);
                                }
                                attachment.ContentId = mimePart.ContentID;
                                Attachments.Add(attachment);
                            }
                        }
                    }

                    // OpaqueMail optional setting for protecting the subject.
                    if (SubjectEncryption && Body.StartsWith("Subject: "))
                    {
                        int linebreakPosition = Body.IndexOf("\r\n");
                        if (linebreakPosition > -1)
                        {
                            subjectText = Body.Substring(9, linebreakPosition - 9);
                            Body        = Body.Substring(linebreakPosition + 2);
                        }
                    }

                    // Set the message's S/MIME attributes.
                    SmimeSigned            = allMimePartsSigned;
                    SmimeEncryptedEnvelope = allMimePartsEncrypted;
                    SmimeTripleWrapped     = allMimePartsTripleWrapped;
                }
                else
                {
                    // Process non-MIME messages.
                    Body = body;
                }
            }

            // Parse String representations of addresses into MailAddress objects.
            if (fromText.Length > 0)
            {
                MailAddressCollection fromAddresses = Functions.FromMailAddressString(fromText);
                if (fromAddresses.Count > 0)
                {
                    From = fromAddresses[0];
                }
            }

            if (toText.Length > 0)
            {
                To.Clear();
                MailAddressCollection toAddresses = Functions.FromMailAddressString(toText);
                foreach (MailAddress toAddress in toAddresses)
                {
                    To.Add(toAddress);
                }

                // Add the address to the AllRecipients collection.
                foreach (MailAddress toAddress in toAddresses)
                {
                    if (!AllRecipients.Contains(toAddress.Address))
                    {
                        AllRecipients.Add(toAddress.Address);
                    }
                }
            }

            if (ccText.Length > 0)
            {
                CC.Clear();
                MailAddressCollection ccAddresses = Functions.FromMailAddressString(ccText);
                foreach (MailAddress ccAddress in ccAddresses)
                {
                    CC.Add(ccAddress);
                }

                // Add the address to the AllRecipients collection.
                foreach (MailAddress ccAddress in ccAddresses)
                {
                    if (!AllRecipients.Contains(ccAddress.Address))
                    {
                        AllRecipients.Add(ccAddress.Address);
                    }
                }
            }

            if (bccText.Length > 0)
            {
                Bcc.Clear();
                MailAddressCollection bccAddresses = Functions.FromMailAddressString(bccText);
                foreach (MailAddress bccAddress in bccAddresses)
                {
                    Bcc.Add(bccAddress);
                }

                // Add the address to the AllRecipients collection.
                foreach (MailAddress bccAddress in bccAddresses)
                {
                    if (!AllRecipients.Contains(bccAddress.Address))
                    {
                        AllRecipients.Add(bccAddress.Address);
                    }
                }
            }

            if (replyToText.Length > 0)
            {
                ReplyToList.Clear();
                MailAddressCollection replyToAddresses = Functions.FromMailAddressString(replyToText);
                foreach (MailAddress replyToAddress in replyToAddresses)
                {
                    ReplyToList.Add(replyToAddress);
                }
            }

            // Decode international strings and remove escaped linebreaks.
            Subject = Functions.DecodeMailHeader(subjectText).Replace("\r", "").Replace("\n", "");
        }
Beispiel #25
0
        public void LoadInfos()
        {
            if (!Client.IsConnected)
            {
                throw new EMailException {
                          ExceptionType = EMAIL_EXCEPTION_TYPE.NOT_CONNECTED
                }
            }
            ;
            Client.Fetch(
                true,
                IMAP_t_SeqSet.Parse(UID),
                new IMAP_t_Fetch_i[] {
                new IMAP_t_Fetch_i_Rfc822()
            },
                (sender, e) =>
            {
                if (e.Value is IMAP_r_u_Fetch)
                {
                    IMAP_r_u_Fetch fetchResp = (IMAP_r_u_Fetch)e.Value;
                    try
                    {
                        if (fetchResp.Rfc822 != null)
                        {
                            fetchResp.Rfc822.Stream.Position = 0;
                            Mail_Message mime = Mail_Message.ParseFromStream(fetchResp.Rfc822.Stream);
                            fetchResp.Rfc822.Stream.Dispose();

                            if (String.IsNullOrWhiteSpace(mime.BodyText))
                            {
                                _TextBody = mime.BodyHtmlText;
                            }
                            else
                            {
                                _TextBody = mime.BodyText;
                            }
                            Attachments.Clear();
                            foreach (MIME_Entity entity in mime.Attachments)
                            {
                                IMAP_Mail_Attachment att = new IMAP_Mail_Attachment();
                                if (entity.ContentDisposition != null && entity.ContentDisposition.Param_FileName != null)
                                {
                                    att.Text = entity.ContentDisposition.Param_FileName;
                                }
                                else
                                {
                                    att.Text = "untitled";
                                }
                                att.Body = ((MIME_b_SinglepartBase)entity.Body).Data;
                                Attachments.Add(att);
                            }
                        }
                    }
                    catch (Exception exe)
                    {
                        throw new EMailException {
                            ExceptionType = EMAIL_EXCEPTION_TYPE.ERROR_ON_GET_MESSAGE, InnerException = exe
                        };
                    }
                }
            }
                );
        }
        public ObservationViewModel(IGALogger logger, IUserInfoService userInfoService, IObservationRepository observationRep,
                                    IHUDProvider hudProvider, IObservationEntryRepository observationEntryRepository,
                                    IObservationChangeRepository observationChangeRepository,
                                    IObservationCommentRepository observationCommentRepository,
                                    IObservationAttachmentRepository observationAttachmentRepository,
                                    IObservationService ObservationService, IDeviceSettings deviceSettings)
        {
            _userInfoService                 = userInfoService;
            _hudProvider                     = hudProvider;
            _observationRep                  = observationRep;
            _observationEntryRepository      = observationEntryRepository;
            _observationChangeRepository     = observationChangeRepository;
            _observationCommentRepository    = observationCommentRepository;
            _observationAttachmentRepository = observationAttachmentRepository;
            _observationService              = ObservationService;
            _deviceSettings                  = deviceSettings;

            TestDate = DateTime.Now;


            MessagingCenter.Subscribe <ObservationChange>(this, "ChangeScreen", (change) =>
            {
                if (Changes == null)
                {
                    Changes = new ObservableCollection <ObservationChange>();
                }
                var item = Changes.Where(m => m == change).FirstOrDefault();
                if (item != null)
                {
                    Changes.Remove(item);
                    Changes.Add(item);
                }
                else
                {
                    Changes.Add(change);
                }
                if (_Navigation.ModalStack.Count != 0)
                {
                    _Navigation.PopModalAsync();
                }
            });

            MessagingCenter.Subscribe <ObservationAttachment>(this, "AttachmentScreen", (attach) =>
            {
                if (Attachments == null)
                {
                    Attachments = new ObservableCollection <ObservationAttachment>();
                }
                var item = Attachments.Where(m => m == attach).FirstOrDefault();
                if (item != null)
                {
                    Attachments.Remove(item);
                    Attachments.Add(item);
                }
                else
                {
                    Attachments.Add(attach);
                }
            });

            MessagingCenter.Subscribe <ObsViewModel>(this, "NumDemUpdate", (change) =>
            {
                RaisePropertyChanged("IndicatorNumCount");
                RaisePropertyChanged("IndicatorDenCount");
                RaisePropertyChanged("IndicatorCount");
                RaisePropertyChanged("IndicatorCountDisplay");
            });



            MessagingCenter.Subscribe <ObservationAttachment>(this, "AttachmentScreenCancel", (change) =>
            {
                if (_Navigation.ModalStack.Count != 0)
                {
                    _Navigation.PopModalAsync();
                }
            });

            MessagingCenter.Subscribe <ObservationChange>(this, "ChangeScreenCancel", (change) =>
            {
                Changes = Changes;
                if (_Navigation.ModalStack.Count != 0)
                {
                    _Navigation.PopModalAsync();
                }
            });

            MessagingCenter.Subscribe <ObservationComment>(this, "CommentScreen", (comment) =>
            {
                var item = Comments.Where(m => m == comment).FirstOrDefault();
                if (item != null)
                {
                    Comments.Remove(item);
                    Comments.Add(item);
                }
                else
                {
                    var i = Comments.Count();
                    Comments.Add(comment);
                }
                if (_Navigation.ModalStack.Count != 0)
                {
                    _Navigation.PopModalAsync();
                }
            });

            MessagingCenter.Subscribe <ObservationComment>(this, "CommentScreenCancel", (change) =>
            {
                Comments = Comments;
                if (_Navigation.ModalStack.Count != 0)
                {
                    _Navigation.PopModalAsync();
                }
            });
        }
Beispiel #27
0
 public virtual void AddAttachment(Attachment attachment)
 {
     attachment.Order = this;
     Attachments.Add(attachment);
 }
        void GetAttachments(MimeMessage message)
        {
            foreach (var mimeEntity in message.Attachments)
            {
                using (var memory = new MemoryStream()){
                    var mimePart = mimeEntity as MimePart;

                    if (mimePart != null)
                    {
                        mimePart.ContentObject.DecodeTo(memory);

                        var attachment = new Attachment {
                            Data     = memory.GetBuffer(),
                            FileName = mimePart.FileName
                        };

                        switch (mimePart.ContentType.MimeType)
                        {
                        case "image/png": {
                            var imageSource = new BitmapImage();
                            imageSource.BeginInit();
                            imageSource.StreamSource = memory;
                            imageSource.EndInit();

                            // Assign the Source property of your image
                            attachment.ImageSource = imageSource;
                            attachment.Extension   = "png";
                            break;
                        }

                        case "image/jpeg": {
                            var image  = Image.FromStream(memory);
                            var bitmap = new Bitmap(image);

                            attachment.ImageSource = BitmapToImageSource(bitmap);
                            attachment.Extension   = "jpg";
                            break;
                        }

                        case "application/ics":
                            attachment.ImageSource = BitmapToImageSource(Resources.Calendar);
                            attachment.Extension   = "ics";
                            break;

                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                            attachment.ImageSource = BitmapToImageSource(Resources.Microsoft_Word);
                            attachment.Extension   = "docx";
                            break;

                        case "application/pdf":
                            attachment.FileName    = mimePart.FileName;
                            attachment.ImageSource = BitmapToImageSource(Resources.PDF);
                            attachment.Extension   = "pdf";
                            break;

                        case "APPLICATION/octet-stream":
                            attachment.FileName    = mimePart.FileName;
                            attachment.Extension   = "dat";
                            attachment.ImageSource = BitmapToImageSource(Resources.PDF);
                            break;

                        default:
                            attachment.FileName    = mimePart.FileName;
                            attachment.ImageSource = BitmapToImageSource(Resources.PDF);
                            break;
                        }

                        Attachments.Add(attachment);
                    }
                }
            }
        }
Beispiel #29
0
 /// <summary>
 /// 添加单个附件
 /// </summary>
 /// <param name="attachment">Attachment附件实例</param>
 public void AddAttachment(Attachment attachment)
 {
     MailValidatorHelper.ValideArgumentNull <Attachment>(attachment, "attachment");
     Attachments.Add(attachment);
 }
Beispiel #30
0
 public void Attach(string attPath)
 {
     Attachments.Add(new Attachment(attPath));
 }
Beispiel #31
0
        /// <summary>
        /// Constructs the binder information from the binder document interface definition.
        /// </summary>
        /// <param name="interfaceType">The binder document interface definition.</param>
        /// <param name="binderAttribute">The definition's <see cref="BinderDocumentAttribute"/>.</param>
        /// <param name="entityDefinitions">The entity definitions keyed by fully qualified defining interface name.</param>
        /// <param name="task">The build task.</param>
        public BinderInfo(Type interfaceType, BinderDocumentAttribute binderAttribute, Dictionary <string, EntityInfo> entityDefinitions, CodeGenerator task)
        {
            var targetNamespace = interfaceType.Namespace;
            var targetName      = interfaceType.Name;

            if (targetName.StartsWith("I"))
            {
                targetName = targetName.Substring(1);
            }

            if (!string.IsNullOrWhiteSpace(binderAttribute.Namespace))
            {
                targetNamespace = binderAttribute.Namespace.Trim();
            }

            if (!string.IsNullOrWhiteSpace(binderAttribute.Name))
            {
                targetName = binderAttribute.Name.Trim();
            }

            Interface  = interfaceType;
            Namespace  = targetNamespace;
            Name       = targetName;
            FullName   = $"{targetNamespace}.{targetName}";
            Visibility = binderAttribute.IsInternal ? "internal" : "public";

            // Perform some binder document checks.

            if (interfaceType.GetInterfaces().Length > 0)
            {
                task.Log.LogError($"Binder document interface [{interfaceType.FullName}] implements another interface.  This is not allowed.");
            }

            EntityInfo targetEntityDefinition;

            if (entityDefinitions.TryGetValue(binderAttribute.EntityType.FullName, out targetEntityDefinition))
            {
                TargetEntityType = targetEntityDefinition.FullName;
            }
            else
            {
                task.Log.LogError($"Binder document interface [{interfaceType.FullName}] references the entity type [{binderAttribute.EntityType.FullName}] which is not tagged with [{nameof(DynamicEntityAttribute)}].");
            }

            // Load the binder's attachment information.

            foreach (var propertyInfo in interfaceType.GetProperties())
            {
                var attachmentAttribute = propertyInfo.GetCustomAttribute <BinderAttachmentAttribute>();

                if (attachmentAttribute == null)
                {
                    task.Log.LogWarning($"Binder document interface [{interfaceType.FullName}] defines a [{propertyInfo.Name}] property without a [{nameof(BinderAttachmentAttribute)}].  This property will be ignored.");
                }

                if (propertyInfo.PropertyType != typeof(string))
                {
                    task.Log.LogError($"Binder document interface [{interfaceType.FullName}] defines a [{propertyInfo.Name}] property that is not defined as a [string].");
                }

                if (propertyInfo.SetMethod != null)
                {
                    task.Log.LogError($"Binder document interface [{interfaceType.FullName}] defines a [{propertyInfo.Name}] property with a setter.");
                }

                if (propertyInfo.GetMethod == null)
                {
                    task.Log.LogError($"Binder document interface [{interfaceType.FullName}] defines a [{propertyInfo.Name}] property without a getter");
                }

                if (string.IsNullOrEmpty(attachmentAttribute.AttachmentName))
                {
                    attachmentAttribute.AttachmentName = propertyInfo.Name;
                }

                Attachments.Add(
                    new AttachmentInfo()
                {
                    PropertyName   = propertyInfo.Name,
                    AttachmentName = attachmentAttribute.AttachmentName ?? propertyInfo.Name
                });
            }
        }
Beispiel #32
0
		/// <summary>
		/// Adds an attachment to the attachments list
		/// </summary>
		/// <param name="filename">The path to the file to be attached</param>
		public void AddAttachment(string filename)
		{
			Attachment attachment = new Attachment(filename);
			Attachments.Add(attachment);
		}