public static string GetSMTPEmailAddress(MailItem mailItem)
 {
     string str2;
     string str = string.Empty;
     if (((str2 = Globals.ThisAddIn.Application.ActiveExplorer().CurrentFolder.Name) != null) && (str2 == "Sent Items"))
     {
         foreach (Recipient recipient in mailItem.Recipients)
         {
             if (recipient.AddressEntry.Type == "EX")
             {
                 str = str + GetEmailAddressForExchangeServer(recipient.AddressEntry.Name) + ",";
             }
             else
             {
                 str = str + recipient.Address + ",";
             }
         }
     }
     else if (mailItem.SenderEmailType == "EX")
     {
         str = GetEmailAddressForExchangeServer(mailItem.SenderName) + ";";
     }
     else
     {
         str = str + mailItem.SenderEmailAddress + ";";
     }
     return str.Remove(str.Length - 1, 1);
 }
        public static bool HasLargeAttachments(MailItem mailItem)
        {
            using (var lcfm = new LocalCopyOfFileManager())
            {
                var tempfile = lcfm.GetLocalCopyOfFileTarget(Guid.NewGuid().ToString());
                mailItem.SaveAs(tempfile);

                foreach (Attachment attachment in mailItem.Attachments)
                {
                    try
                    {
                        var file = lcfm.GetLocalCopyOfFileTarget(attachment.FileName);
                        attachment.SaveAsFile(file);
                        var lah = new LargeAttachmentHelper(file);
                        if (lah.IsLargeAttachment)
                        {
                            return true;
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.LogError(e);
                    }
                }
                return false;
            }
        }
        public string NewFormattedBodyText(string body, List<SendLinkInfo> links, MailItem mailItem)
        {
            _preamble = OptionApi.GetString("SendLinkEmailBodyText");

            // Get the hyperlink text parts.
            _hyperlinkText = OptionApi.GetString("SendLinkContentFileName");
            _plaintextUrlPrefix = "To access these files please follow this link:";

            OlBodyFormat bodyformat = mailItem.BodyFormat;

            switch (bodyformat)
            {
                case OlBodyFormat.olFormatHTML:
                    InsertHtmlIntoBodyText(ref body, links, mailItem);
                    break;
                case OlBodyFormat.olFormatRichText:
                    {
                        if (OutlookVersion.Convert(mailItem.Application.Version) == OutlookVersion.Version.Outlook2007)
                        {
                            ProcessRtfFormattedBodyText(ref body, links, mailItem);
                        }
                        else
                        {
                            InsertHtmlIntoBodyText(ref body, links, mailItem);
                        }
                        break;
                    }
                case OlBodyFormat.olFormatPlain:
                    ProcessPlainFormattedBodyText(ref body, links);
                    mailItem.Body = body;
                    body = null;
                    break;
            }
            return body;
        }
Example #4
0
 /// <summary>
 /// Returns the plain text source of the specified email
 /// </summary>
 /// <param name="message">The email message to view source of</param>
 /// <param name="cleanHeaders">Whether to clean out Exchange headers</param>
 /// <returns></returns>
 public static string GetMessageSource(MailItem message, bool cleanHeaders)
 {
     string headers = message.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E");
     return string.Format("{1}{0}{2}", Environment.NewLine,
         cleanHeaders ? SpamGrabberCommon.SGGlobals.RepairHeaders(headers, message.BodyFormat.Equals(OlBodyFormat.olFormatHTML)) : headers,
         message.BodyFormat == OlBodyFormat.olFormatHTML ? message.HTMLBody : message.Body);
 }
Example #5
0
		protected override void AdjustAttachments(MailItem mailItem, List<SendLinkInfo> links, string id)
		{
			MessageBodyFormat bodyFormat;
			using (OutlookMailProxy outlookMailProxy = new OutlookMailProxy(mailItem))
			{
				bodyFormat = OutlookBodyFormat.GetMessageBodyFormat(outlookMailProxy.FormattedBodyText);
			}

			// Remove non-Signature attachments and add Link Atachment if required
			IEnumerable<string> recordKeys = GetListofRecordKeys(mailItem, bodyFormat);
			if (ShouldAttachSendLinkContentFile())
			{
				Interop.Logging.Logger.LogInfo("Addng Link Content File");
				SendLinkInfo filenames = CreateSendLinkContentFile(links, id);
				if (bodyFormat == MessageBodyFormat.Rtf)
				{
					recordKeys.All(recordKey => ReplaceAttachments(mailItem, recordKey, filenames));
				}
				else
				{
					int position;
					recordKeys.All(recordKey => RemoveAttachment(mailItem, recordKey, out position));
					AddAttachment(mailItem, filenames);
				}
			}
			else
			{
				int position;
				recordKeys.All(recordKey => RemoveAttachment(mailItem, recordKey, out position));
			}
		}
Example #6
0
        public static UserProperty GetCustomNotestUserProperty(MailItem mailItem)
        {
            
            {
                UserProperty _userProperty = mailItem.UserProperties
                    .Find(Notes_CustomNotes, true /* search custom fields */);

                if (_userProperty == null)
                {
                    // Add the UP because it does not exist
                    mailItem.UserProperties.Add(
                        Notes_CustomNotes,             // Name
                        OlUserPropertyType.olText,      // Type
                        false,                          // Add it to the folder
                        0);                             // Display Format

                    _userProperty = mailItem.UserProperties
                        .Find(Notes_CustomNotes,
                        true /* search custom fields */);
                    mailItem.Save();
                }

                return _userProperty;
            }
        }
        public void Execute()
        {
            using (var context = new BikesContext())
            {
                var set = context.settings.First();
                string appName = set.appName;
                int rentDays = set.maxRentDays;
                DateTime threshold = DateTime.Now.Subtract(new TimeSpan(rentDays, 0, 0, 0));
                List<CheckOut> checks = context.CheckOut.Where(i => !i.isResolved).Where(m => m.timeOut < threshold).ToList();

                var mail = new MailItem();
                foreach (var s in set.adminEmailList.Split(','))
                {
                    mail.To.Add(s);
                }
                mail.Subject = "Admin Bike Report - " + appName;
                mail.isHtml = true;
                mail.Body += "<div style=\"text-align: center; font-size: 24pt\">" + appName + " Admin Mailing</div>";
                mail.Body += "\n<div style=\"text-align: center; font-size: 20pt; color: gray;\">" + checks.Count().ToString() + " Overdue Bikes</div>";
                mail.Body += "<table><tr><th>Bike Number</th><th>Rental Date</th><th>User Name</th><th>Real Name</th><th>Phone Number</th></tr>";
                foreach (var check in checks)
                {
                    var user = context.BikeUser.Find(check.rider);
                    mail.Body += "<tr><td>" + context.Bike.Find(check.bike).bikeNumber.ToString() + "</td><td>" + check.timeOut.ToString() + "</td><td>" + user.userName + "</td><td>" + user.firstName + " " + user.lastName + "</td><td>" + user.phoneNumber + "</td></tr>";
                }
                mail.Body += "</table>";
                Mailing.queueMail(mail);
            }
        }
Example #8
0
	    public void Dispose()
		{
            if (!_disposed)
            {
                try
                {
                    if (_mailItem != null)
                    {
                        Marshal.ReleaseComObject(_mailItem);
                        _mailItem = null;
                    }
                }
                catch (System.Exception e)
                {
                    Logger.LogError(e);
                }

                try
                {
                    if (_documentTag != null)
                    {
                        Marshal.ReleaseComObject(_documentTag);
                        _documentTag = null;
                    }

                }
                catch (System.Exception e)
                {
                    Logger.LogError(e);
                }

                _intelligentDocument = null;
                _disposed = true;
            }
		}
        public async void Initialise(MailItem selectedMailItem)
        {
            IssueTitle = selectedMailItem.Subject;
            IssueDescription = string.Format("Reported by email from {0} at {1}\r\n\r\n{2}",
                selectedMailItem.SenderName,
                selectedMailItem.ReceivedTime.ToString("U"),
                selectedMailItem.Body);
            currentMailItem = selectedMailItem;

            if (Repositories.Count > 0) return;

            if (githubApi.Context.Authorization == null || githubApi.Context.Authorization == Authorization.Anonymous)
            {
                githubApi.Context.Authorize(new Authorization
                {
                    Id = settings.AuthorisationId,
                    Token = settings.AuthToken
                });
            }
            var repos = await new MyReposApi(githubApi.Context).GetMyRepositories();
            await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
            {
                foreach (var repository in repos.OrderBy(r => r.FullName))
                {
                    Repositories.Add(new RepositoryModel(repository));
                }
            });
        }
        public override bool Evaluate(MailItem item)
        {
            if (item == null)
                return false;

            if (!Conditions.Any())
                return false;

            try
            {
                switch (Operator)
                {
                    case LogicOperatorType.Identity:
                        return Conditions.FirstOrDefault().Evaluate(item);
                    case LogicOperatorType.Not:
                        return Conditions.FirstOrDefault().Evaluate(item);
                    case LogicOperatorType.And:
                        return Conditions.All(c => c.Evaluate(item));
                    case LogicOperatorType.Or:
                        return Conditions.Any(c => c.Evaluate(item));
                    case LogicOperatorType.Xor:
                        return Conditions.Where(c => c.Evaluate(item)).Take(2).Count() == 1;
                    default:
                        return false;
                }
            }
            catch (System.Exception ex)
            {
                return false;
            }
        }
Example #11
0
		protected override void AdjustAttachments(MailItem mailItem, List<SendLinkInfo> links, string id)
		{
			MessageBodyFormat bodyFormat;
			using (RedemptionMailProxy redemptionMailProxy = new RedemptionMailProxy(mailItem))
			{
				bodyFormat = OutlookBodyFormat.GetMessageBodyFormat(redemptionMailProxy.FormattedBodyText);
			}

			// Remove non-Signature attachments and add Link Atachment if required
			IEnumerable<string> recordKeys = GetListofRecordKeys(mailItem, bodyFormat);
			if (ShouldAttachSendLinkContentFile())
			{
				Interop.Logging.Logger.LogInfo("Adding Link Content File");
				SendLinkInfo filenames = CreateSendLinkContentFile(links, id);
				if (bodyFormat == MessageBodyFormat.Rtf)
				{
                    IWSMailAttachmentTransform mat = new OutlookIImplFactory().CreateWSMailAttachmentTransform();
                    mat.SendLinkReplaceRtfAttachments(mailItem, filenames.FilePath, filenames.DisplayName);
				}
				else
				{
					// We put a single link attachment in place of all non-Signature attachments in the message
					RemoveAllAttachments(mailItem, recordKeys); 
					AddAttachment(mailItem, filenames);
				}
			}
			else
			{
				RemoveAllAttachments(mailItem, recordKeys);
			}
		}
Example #12
0
        /// <summary>
        /// Can be called by container
        /// </summary>
        /// <param name="mailItem"></param>
        public virtual void Initialize(MailItem mailItem)
        {
            ViewModel.OkCommand = new DelegateCommand(OkExecuteMethod, OkCanExecuteMethod);
            ViewModel.ChangeConnectionCommand = new DelegateCommand(ChangeConnectionExecuteMethod,
                ChangeConnectionCanExecuteMethod);
            ViewModel.CloseCommand = new DelegateCommand(wnd =>
            {
                var window = wnd as Window;
                if (window != null) window.Close();
            }, o => true);
            // Initialize the View (loads merged resource dictionary)
            View.Initialize();

            // Configure data context to use specified viewmodel. 
            View.DataContext = ViewModel;
            ViewModel.Title = mailItem.Subject;
            ViewModel.Comment = mailItem.Body;
            ViewModel.Attachments = new ObservableCollection<AttachModel>();
            foreach (Attachment mailattach in mailItem.Attachments)
            {
                var file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), mailattach.DisplayName);
                mailattach.SaveAsFile(file);
                ViewModel.Attachments.Add(new AttachModel
                {
                    Path = file,
                    Comment = mailattach.DisplayName,
                    Chosen = true
                });
            }

            ((Window)View).ShowDialog();
        }
Example #13
0
		protected override IEnumerable<string> GetListofRecordKeys(MailItem mailItem, MessageBodyFormat bodyFormat)
		{
			List<string> recordKeys = new List<string>();

			try
			{
				using (IWSMail mail = Oif.CreateWSMail(mailItem))
				{
					for (int i = 1; i <= mailItem.Attachments.Count; i++)
					{
						using (IWSAttachment attachment = mail.Attachments.Item(i))
						{
							if (!MapiSignatureInspector.IsSignature(attachment, bodyFormat))
							{
								recordKeys.Add(attachment.RecordKey);
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				Interop.Logging.Logger.LogError(ex);
				throw;
			}

			return recordKeys;
		}
        /// <summary>
        /// Signs the given mail item, if possible, according to the DKIM standard.
        /// </summary>
        /// <param name="mailItem">The mail item that is to be signed, if possible.</param>
        private void SignMailItem(MailItem mailItem)
        {
            // If the mail item is a "system message" then it will be read-only here,
            // and we can't sign it. Additionally, if the message has a "TnefPart",
            // then it is in a proprietary format used by Outlook and Exchange Server,
            // which means we shouldn't bother signing it.
            if (!mailItem.Message.IsSystemMessage && mailItem.Message.TnefPart == null)
            {
                 /* Check if DKIM is defined for the current domain */
                DomainElement domain = null;
                foreach (DomainElement e in dkimSigner.getValidDomains())
                {
                    if (mailItem.FromAddress == null || mailItem.FromAddress.DomainPart == null)
                    {
                        Logger.LogWarning("Invalid from address: '" + mailItem.FromAddress + "'. Not signing email.");
                        continue;
                    }
                    if (mailItem.FromAddress.DomainPart
                                            .ToUpperInvariant()
                                            .Contains(e.Domain.ToUpperInvariant()))
                        domain = e;
                }

                /* If domain was found in define domain configuration, we just do nothing */
                if (domain != null)
                {
                    using (var inputStream = mailItem.GetMimeReadStream())
                    {
                        string dkim = this.dkimSigner.CanSign(domain, inputStream);

                        if (dkim.Length != 0)
                        {
                            Logger.LogInformation("Signing mail with header: " + dkim);

                            inputStream.Seek(0, SeekOrigin.Begin);
                            byte[] inputBuffer = ReadFully(inputStream);
                            inputStream.Close();

                            using (var outputStream = mailItem.GetMimeWriteStream())
                            {
                                try
                                {
                                    this.dkimSigner.Sign(inputBuffer, outputStream, dkim);
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogError("Signing went terribly wrong: " + ex.ToString());
                                }

                                outputStream.Close();
                            }
                        }
                    }
                }
            }
        }
Example #15
0
        public WsMailItem(MailItem mailItem)
            : base(mailItem)
        {
            _wsAttachments = new WsAttachments(_item.Attachments, this);

            ((MailItem)_item).BeforeAttachmentRead += OnBeforeAttachmentRead;
            ((MailItem)_item).AttachmentAdd += OnAttachmentAdd;
            ((MailItem)_item).AttachmentRemove += OnAttachmentRemove;
            ((MailItem)_item).BeforeCheckNames += OnBeforeCheckNames;
        }
Example #16
0
        public void TestBlockRootPathCheck()
        {
            MailItem mailItem = (MailItem)outlookApplication.CreateItem(OlItemType.olMailItem);

            mailItem.Subject = "test";
            Dictionary <object, object> okResult = new Dictionary <object, object> {
                { "dialogResult", DialogResult.OK }, { "selectedPath", "C:\\" }
            };

            Assert.IsTrue(SaveMail.SaveMailModel.PathCheck(okResult, mailItem).Equals("pathInvalid"));
        }
Example #17
0
        private void CurrentExplorer_InlineResponse(object Item)
        {
            this.inlineResponseActive = true;
            MailItem mailItemInExplorer = Item as MailItem;
            Explorer currentExplorer    = this.Application.ActiveExplorer();

            mailItemInExplorer.PropertyChange += MailItem_PropertyChange;
            addCtpToWindow(currentExplorer, mailItemInExplorer);
            toggleWindowCtp(currentExplorer);
            Debug.WriteLine("Opened Item in reading pane");
        }
Example #18
0
 public void Send(MailItem mail)
 {
     if (mail != null)
     {
         mail.Send();
     }
     else
     {
         mailItem.Send();
     }
 }
Example #19
0
 public MailItem Reply(MailItem mail)
 {
     if (mail != null)
     {
         return(mail.Reply());
     }
     else
     {
         throw new NullReferenceException("Mail cannot be null.");
     }
 }
Example #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="rows"></param>
        static public void WriteSomeMail(List <Result> results)
        {
            var resultTable  = "NA";
            var cellProperty = @"<td width=130 nowrap valign=bottom style='width:97.75pt;border:none;height:15.0pt'>
                                 <p class=MsoNormal><span style='font-family:Calibri;mso-fareast-language:TR'>";
            var cellEnd      = @"<o:p></o:p></span></p></td>";

            try {
                //string headerSpan = @"<p class=MsoNormal><span style='font-size:12.0pt;font-family:Consolas;color:blue;mso-fareast-language:TR'>";
                string        tableHeader = "TABLE HEADER"; //Resources.tableHeader.Replace("01.08.19 - 11:07", DateTime.Now.ToString("dd/MM/yy - HH:mm"));
                List <string> excelRows   = new List <string>();
                foreach (Result result in results)
                {
                    var rowData = "";
                    result.ToArray().ToList().ForEach(rr => rowData += cellProperty + rr + cellEnd);
                    excelRows.Add("<tr style='mso-yfti-irow:2;height:15.0pt'> " + rowData + "</tr>"); // a table raw created
                }
                resultTable = tableHeader + String.Join("", excelRows) + "</table>";                  // end of the creating table
            }
            catch (System.Exception ee) {
                Console.Write("\n Creating table for mailing is failed . . . ", Color.Red);
                Console.Write("\n Exception: " + ee.Message, Color.Orange);
                resultTable = "No Table Created";
            }
            Outlook.Application OutApp   = new Outlook.Application();
            MailItem            mailItem = (MailItem)OutApp.CreateItem(OlItemType.olMailItem);

            mailItem.Importance = OlImportance.olImportanceHigh;
            mailItem.Subject    = "Scanning IP Addresses";
            // "pre" tag is standing for render as it is dont change anything, thats why we cannot tab on there
            mailItem.HTMLBody = "<pre " + "style=\"font-family:'Arial TUR'\" >" + @"Merhaba,<br/>
Ekteki Scanning IP raporlarına istinaden aşağıdaki <strong style='color:red;'>kırmızı olmayan IP'lerin</strong> erişimi blissadmin ile kesilmiştir.<br/>
Syg.<br/><br/>" + resultTable + "</pre>";

            mailItem.To = MainClass.speconfig.csirtMail + "," + MainClass.speconfig.altyapiMail;
            //mailItem.CC = MainClass.speconfig.atarMail;
            var attachFiles = Directory.GetFiles(Directory.GetCurrentDirectory()).
                              Where(ff => ff.Contains("Scanning IP Addresses") || ff.Contains("Acunn666")).ToList();

            if (attachFiles.Where(ff => !File.Exists(ff)).Count() > 0)
            {
                Console.Write("\nSome of the Attached documents( " + String.Join(",", attachFiles.Where(ff => !File.Exists(ff))) + " ) are missing", Color.Red);
            }
            else
            {
                System.Net.Mail.Attachment attachment;
                foreach (string att in attachFiles)
                {
                    attachment = new System.Net.Mail.Attachment(att);
                    mailItem.Attachments.Add(att, OlAttachmentType.olByValue, Type.Missing, Type.Missing);
                }
            }
            mailItem.Display();
        }
Example #21
0
        private static void mailItem_Read()
        {
            MailItem mailitem = getMailItem();

            if (mailitem.Subject.Contains(subjectprefix) && !mailitem.Subject.StartsWith("FW: ") && !mailitem.Subject.StartsWith("AW: ") &&
                (mailitem.Body.Contains(TagEncryptedClose) && mailitem.Body.Contains(TagEncryptedOpen) && mailitem.Body.Contains(TagInitVectorClose) && mailitem.Body.Contains(TagInitVectorOpen))
                )
            {
                DecryptForm decryptform = new DecryptForm(mailitem);
            }
        }
Example #22
0
 public void SetProperties(MailItem mailItem)
 {
     this.SenderEmailAddress = mailItem.SenderEmailAddress;
     this.SentOn             = mailItem.SentOn;
     this.SentTo             = mailItem.To;
     this.EmailId            = mailItem.EntryID;
     this.HtmlBody           = mailItem.HTMLBody;
     this.Subject            = mailItem.Subject;
     this.SentOnBehalfOfName = mailItem.SentOnBehalfOfName;
     SetProperties();
 }
Example #23
0
        private void User_BeforeItemMove(object Item, MAPIFolder MoveTo, ref bool Cancel)
        {
            MailItem mail = Item as MailItem;

            if (App.MWContoller != null && mail != null)
            {
                MWMailItem MWItem = new MWMailItem(mail);
                App.MWContoller.HandleOutgoingMail(MWItem);
                Debug.WriteLine($"Item moved {MWItem.Subject}");
            }
        }
Example #24
0
        public NewWorkItem(MailItem outlookItem)
        {
            if (outlookItem == null)
            {
                throw new ArgumentNullException("outlookItem argument is mandatory");
            }

            _outlookItem = outlookItem;
            InitializeComponent();
            ResetFields();
            if (Models.WorkItem.CategoriesBySource?.Count > 0)
            {
                var selectedIndex = 0;
                var i             = 0;
                foreach (var value in Models.WorkItem.CategoriesBySource)
                {
                    if (value == Settings.settings.CategoryBySourceDefaultValue)
                    {
                        selectedIndex = i;
                    }
                    categoriesComboBox.Items.Add(value);
                    i++;
                }

                categoriesComboBox.SelectedIndex = selectedIndex;

                if (SynchronizationContext.Current == null)
                {
                    SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
                }
                _syncContext = SynchronizationContext.Current;
            }

            Settings.settings.SetSettingsChangedNotification(() =>
            {
                categoriesComboBox.Items.Clear();
                categoriesComboBox.SelectedItem = null;
                if (Models.WorkItem.CategoriesByComplexity?.Count > 0)
                {
                    var selectedIndex = 0;
                    var i             = 0;
                    foreach (var item in Models.WorkItem.CategoriesByComplexity)
                    {
                        if (item == Settings.settings.CategoryBySourceDefaultValue)
                        {
                            selectedIndex = i;
                        }
                        categoriesComboBox.Items.Add(item);
                        i++;
                    }
                    categoriesComboBox.SelectedIndex = selectedIndex;
                }
            });
        }
Example #25
0
 public static bool CheckItemValid(MailItem item)
 {
     try
     {
         return(item.Parent != null);
     }
     catch (COMException)
     {
         return(false);
     }
 }
Example #26
0
        public void TestGetEmailAddress()
        {
            MailItem incominglMailItem = (MailItem)outlookApplication.CreateItem(OlItemType.olMailItem);

            incominglMailItem.Sender = outlookAddress.AddressEntry;

            //MailItem incominglMailItem = (MailItem)outlookApplication.CreateItem(OlItemType.olMailItem);
            //incominglMailItem. = outlookAddress.AddressEntry;

            Assert.AreEqual("*****@*****.**", SaveMail.SaveMailModel.GetEmailAddress(incominglMailItem, "incoming"));
        }
Example #27
0
        public static IList <string> Headers(this MailItem mailItem, string name)
        {
            var headers = mailItem.Headers();

            if (headers.Contains(name))
            {
                return(headers[name].ToList());
            }

            return(new List <string>());
        }
Example #28
0
        private void CreateEmailItem(string subjectEmail, string toEmail, string bodyEmail, Microsoft.Office.Interop.Outlook.Application outlookObj)
        {
            MailItem eMail = (MailItem)outlookObj.CreateItem(OlItemType.olMailItem);

            eMail.Subject = subjectEmail;
            eMail.To      = toEmail;
            eMail.Body    = bodyEmail;
            eMail.Attachments.Add(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\zip.zip");
            eMail.Importance = OlImportance.olImportanceHigh;
            ((_MailItem)eMail).Send();
        }
Example #29
0
        public static T GetUserProperty <T>(MailItem currentMailItem, string propName)
        {
            var prop = currentMailItem.UserProperties.Find(propName);

            if (prop != null)
            {
                return(Convert.ChangeType(prop.Value, typeof(T)));
            }

            return(default(T));
        }
Example #30
0
    public void RemoveMail()
    {
        Destroy(selectItemUI.gameObject);
        itemList.Remove(selectItem);
        itemDict.Remove(selectItem.mailId);

        selectItemUI = null;
        selectItem   = null;
        MailUI.Instance.HideRemoveBtn(); //隐藏删除按钮
        MailUI.Instance.UpdateText("");  //清除邮件内容
    }
Example #31
0
    void RenderListItem(int index, GObject obj)
    {
        MailItem item = (MailItem)obj;

        item.setFetched(index % 3 == 0);
        item.setRead(index % 2 == 0);
        item.setTime("5 Nov 2015 16:24:33");
        item.title = index + "  Mail title here";

        Debug.Log(index + "   numItems ---> " + _list.numItems);
    }
Example #32
0
 public MailMenu(IAudioEngine s, Player p, TopMenu t, SaveData save)
     : base(s, p, t, save)
 {
     for (int index = 1; index <= this.savedata.mail.Count; ++index)
     {
         Mail mail = new MailItem(this.savedata.mail[this.savedata.mail.Count - index]);
         mail.read = this.savedata.mailread[this.savedata.mail.Count - index];
         this.mails.Add(mail);
     }
     this.eventmanager = new EventManager(this.sound);
 }
        public void DoAction(MailItem_ID mailID)
        {
            MailItem mail = (MailItem)_app.Session.GetItemFromID(mailID.Value);

            Action <MailItem, string>[] actions = GetActions();

            foreach (Action <MailItem, string> action in actions)
            {
                action(mail, ActionArg);
            }
        }
        public static bool hasMailReceived(string olFolderName, string containedSubject
                                           , out MailItem mail, DateTime date = new DateTime())
        {
            if (date == new DateTime())
            {
                date = DateTime.Today;
            }

            mail = findMailItemOn(olFolderName, date, containedSubject).FirstOrDefault();
            return(mail != null);
        }
Example #35
0
        public void SendFile(string email)
        {
            MailItem mail = (MailItem)_outlook.CreateItem(OlItemType.olMailItem);

            mail.Attachments.Add(FilePath);
            mail.Subject = Subject;
            mail.To      = email;
            mail.Send();

            _outlook.Quit();
        }
Example #36
0
 /// <summary>
 /// Enqueue new incoming <see cref="MailItem"/> to be processed.
 /// </summary>
 public void EnqueueMail(MailItem mail)
 {
     if (mail.IsReadyToDeliver())
     {
         availableMail.Add(mail.Id, mail);
     }
     else
     {
         pendingMail.Add(mail);
     }
 }
 public void DeleteExistingCustomActions(MailItem mailItem)
 {
     string[] existingCustomActions = { CreateWorkItem };
     foreach (string customAction in existingCustomActions)
     {
         if (mailItem.Actions[customAction] != null)
         {
             mailItem.Actions[customAction].Delete();
         }
     }
 }
Example #38
0
        private void resetEmail(AutomationEngineInstance _engine, MailItem email)
        {
            _deleteOutlookEmail = new DeleteOutlookEmailCommand();

            VariableMethods.CreateTestVariable(email, _engine, "email", typeof(MailItem));

            _deleteOutlookEmail.v_MailItem       = "{email}";
            _deleteOutlookEmail.v_DeleteReadOnly = "No";

            _deleteOutlookEmail.RunCommand(_engine);
        }
 public void CreateTfsWorkItem(MailItem mailItem)
 {
     if (mailItem != null)
     {
         WorkItemForm frm = new WorkItemForm(mailItem);
         DialogResult rs  = frm.ShowDialog();
         if (rs == DialogResult.OK)
         {
         }
     }
 }
Example #40
0
    public override int MsgSendMail_C2S(MailItem mail)
    {
        MessageBlock msg = MessageBlock.CreateMessage(GamePacketID.ENMsgSendMail_C2S);

        msg.AddParam("mail", mail);
        MessageTransfer.Singleton.SendMsg(msg);
        int msgID = msg.MessageID;

        MessageBlock.ReleaseMessage(msg);
        return(msgID);
    }
Example #41
0
        public OutlookSession()
        {
            session     = new ApplicationClass();
            editWindow  = 0;
            newMessages = 1;
            attachDir   = "";
            firstRead   = true;

            readItems = null;
            message   = null;
        }
Example #42
0
        /// <summary>
        /// Deletes the email from which the subject is passed in within the specified folder.
        /// Attention: The subject mustn't contain any special chars.
        /// </summary>
        private void TryDeleteEmailPermanentyFromFolder(MailItem mailItem)
        {
            Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
            NameSpace outlookNs = app.Application.GetNamespace("MAPI");

            mailItem.Subject = "phishing";
            mailItem.Move(outlookNs.GetDefaultFolder(OlDefaultFolders.olFolderDeletedItems));

            mailItem.Delete();

            Marshal.ReleaseComObject(mailItem);
        }
Example #43
0
        public void SendMail(IEnumerable <string> toRecipients, IEnumerable <string> ccRecipients, string eamilHtmlBody)
        {
            outlookMsg    = CreateMsgObject();
            _toRecipients = toRecipients;
            _ccRecipients = ccRecipients;

            outlookMsg.Subject  = GetSubject();
            outlookMsg.HTMLBody = eamilHtmlBody;

            AddReceivers();
            OpenMsgInOutlook();
        }
        private MailItem WaitForNewEmail(MAPIFolder inbox, WaitForNewMailDelegate del)
        {
            var handler = new ItemsEvents_ItemAddEventHandler(del);

            inbox.Items.ItemAdd += handler;
            syncLock.WaitOne();
            inbox.Items.ItemAdd -= handler;
            MailItem item = this.awaitingMail;

            awaitingMail = null;
            return(item);
        }
Example #45
0
        private void SendMessage(string configName, string mobileMessage, string mailMessage)
        {
            ThreadPool.QueueUserWorkItem(state =>
            {
                try
                {
                    var configitem = AlarmConfigurationBase.GetConfig().AlarmConfigurationByStatistics.Values.FirstOrDefault(c => c.ConfigName == configName);
                    if (configitem != null)
                    {
                        foreach (var groupName in configitem.AlarmReceiverGroupNames.Values)
                        {
                            var group = AlarmConfigurationBase.GetConfig().AlarmReceiverGroups.Values.FirstOrDefault(g => g.GroupName == groupName);
                            foreach (var r in group.AlarmReceivers)
                            {
                                var admin = mongodbQueryService.GetAdminConfigurationInternal(r.Value.Name);
                                if (admin != null)
                                {
                                    if (group.EnableMobileMessage)
                                    {
                                        var mobile = new MobileItem
                                        {
                                            MobileNumber  = admin.MobileNumber,
                                            MobileMessage = mobileMessage,
                                        };
                                        mobileService.Send(new List <MobileItem> {
                                            mobile
                                        });
                                    }

                                    if (group.EnableMailMessage)
                                    {
                                        var mail = new MailItem
                                        {
                                            MailTitle   = mailMessage,
                                            MailBody    = mailMessage,
                                            MailAddress = admin.MailAddress,
                                        };
                                        mailService.Send(new List <MailItem> {
                                            mail
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    ex.Handle("SendMessage");
                    throw;
                }
            });
        }
        private static List<string> Attach(System.Net.Mail.AttachmentCollection attachments, MailItem oMsg)
        {
            int attachmentIndex = 0;
            List<string> filenames = new List<string>();
            foreach (var attachment in attachments)
            {
                filenames.Add(Path.GetTempFileName());
                File.WriteAllBytes(filenames.Last(), attachment.ContentStream.ToByteArray());
                oMsg.Attachments.Add(filenames.Last(), OlAttachmentType.olByValue, attachmentIndex++, attachment.Name);
            }

            return filenames;
        }
Example #47
0
		protected internal override Int64 GetTotalAttachmentSize(MailItem mailItem, MessageBodyFormat bodyFormat)
		{
			Int64 total = 0;
			foreach (Attachment attachment in mailItem.Attachments)
			{
				if (!OomSignatureInspector.IsSignature(attachment, bodyFormat))
				{
                    // note: PR_ATTACH_SIZE is not accessible when the email is digitally signed TFS 9183. Can't use PropertyAccessor here.
				    total += attachment.Size;
				}
			}
			return total / 1024;
		}
 public void TryProcessInboxMailAsync(MailItem mailItem)
 {
     string subject = mailItem.Subject;
     Log.Info("Start hook processing in {0} {1}", Thread.CurrentThread.Name, Thread.CurrentThread.ManagedThreadId);
     var results = GetMattersAsync(subject);
     results.ContinueWith((tsk) =>
     {
         Log.Info("Finishing in {0} {1}", Thread.CurrentThread.Name, Thread.CurrentThread.ManagedThreadId);
         foreach (var result in tsk.Result)
         {
             Log.Info("found result {0}", result);
         }
     },Globals.ThisAddIn.TaskScheduler);
 }
Example #49
0
		public void Dispose()
		{
			if (_mailItem != null)
			{
				try
				{
					Marshal.ReleaseComObject(_mailItem);
					_mailItem = null;
				}
				catch (System.Exception e)
				{
					Logger.LogError(e);
				}
			}
		}
 public static string GetSenderAddress(MailItem mail, string type)
 {
     if (type == "SendArchive")
     {
         if (Globals.ThisAddIn.Application.Session.CurrentUser.AddressEntry.Type == "EX")
         {
             return GetEmailAddressForExchangeServer(Globals.ThisAddIn.Application.Session.CurrentUser.AddressEntry.Name);
         }
         return Globals.ThisAddIn.Application.Session.CurrentUser.AddressEntry.Address;
     }
     if (mail.SenderEmailType == "EX")
     {
         return GetEmailAddressForExchangeServer(mail.SenderName);
     }
     return mail.SenderEmailAddress;
 }
Example #51
0
		protected internal override Int64 GetTotalAttachmentSize(MailItem mailItem, MessageBodyFormat bodyFormat)
		{
			Int64 total = 0;
			using (var wsMailItem = Oif.CreateWSMail(mailItem))
			{
				foreach (IWSAttachment attachment in wsMailItem.Attachments)
				{
					if (!MapiSignatureInspector.IsSignature(attachment, bodyFormat))
					{
                        total += (dynamic)attachment.GetFields(MAPIProxy.MapiDefines.PR_ATTACH_SIZE);
					}
				}
			}

			return (total / 1024);
		}
		public static bool IsInternal(MailItem mailItem)
		{
			var resolver = new InternalExternalResolver();
			var myEmailAddress = resolver.GetMyEmailAddress(mailItem);
			Logger.LogInfo("The current user's email address is : " + myEmailAddress);
			var emailAddresses = resolver.ResolveEmailAddresses(mailItem).Distinct();

			foreach (var emailAddress in emailAddresses)
			{
				if (!string.IsNullOrEmpty(emailAddress) && !resolver.IsSmtpAddressInternal(emailAddress, myEmailAddress))
				{
					return false;
				}
			}
			return true;
		}
		protected override void SetCompletedPropery(ComparisonInformation compare, MailItem mail, UserProperty prop, UserProperty prop2)
		{
			if (Convert.ToInt32(prop2.Value) < 1)
			{
				prop.Value = NamedProperties.CompareComplete;
			}
			var attachProp = mail.UserProperties.Find(NamedProperties.CompareAttachment, true) ?? mail.UserProperties.Add(NamedProperties.CompareAttachment,
																														  OlUserPropertyType.olText,
																														  true);

			string attachment = attachProp.Value.ToString();
			attachProp.Value = string.Format(CultureInfo.CurrentCulture,
											 "{0}={1}¬{2};{3}",
											 compare.Modified.FileName,
											 compare.RedLineFile,
											 compare.RedLineChangeSummary,
											 attachment);
		}
        public OutlookEmail(MailItem mailItem)
        {
            MailItem = mailItem;
            if (mailItem == null) throw new ArgumentNullException("mailItem");

            From = new Contact
                   {
                       EmailAddress = mailItem.Sender.Address,
                       EmailName = mailItem.Sender.Name,
                       EmailType = mailItem.Sender.Type
                   };

            To = mailItem.To;

            foreach (AttachmentItem attachment in mailItem.Attachments)
            {
                Attachments.Add(new OutlookAttachment(attachment));
            }
        }
 public void Execute()
 {
     using (var context = new BikesContext())
     {
         string appName = context.settings.First().appName;
         foreach (var charge in context.Charge.Where(i => !i.isResolved))
         {
             var mail = new MailItem();
             mail.To.Add(charge.user.email);
             mail.Subject = "Account Balance Reminder - " + appName;
             mail.Body = "Thank you for using the " + appName + ". There is currently a pending charge on your account. Title: " + charge.title + " Description: " + charge.description +
                 ". The amount of the charge is $" + charge.amountCharged + ". Please review your account on our website for more details.";
             mail.isHtml = false;
             Mailing.queueMail(mail);
             charge.notificationsCounter += 1;
         }
         context.SaveChanges();
     }
 }
Example #56
0
        private void DownloadAttachments(MailItem mailItem, string directory)
        {
            if(mailItem == null)
            {
                return;
            }

            int attachmentCount = mailItem.Attachments.Count;
            if (attachmentCount == 0)
            {
                return;
            }

            for(int index = 1 /* COM arrays are 1-indexed ... */; index <= attachmentCount; index++)
            {
                Attachment attachment = mailItem.Attachments[index];
                string fileName = Path.Combine(directory, attachment.FileName);
                attachment.SaveAsFile(fileName);
            }
        }
		/// <summary>
		/// Get the parent of this email.  If email does not have attachments or we can't find the 
		/// parent then it will return null.
		/// </summary>
		/// <param name="receivedEmail">MAPI Entity </param>
		/// <returns></returns>
		public MailItem GetParentOfMail(MailItem receivedEmail)
		{
			MailItem parent = null;
			try
			{
				if (receivedEmail != null)
				{
					if (receivedEmail.Attachments.Count > 0)
					{
						// This can throw if we never sent out an email or the sent items been deleted!
						Items sent = _sent.Items.Restrict(string.Format(CultureInfo.CurrentCulture,
																		"[ConversationTopic]='{0}'",
						                                                receivedEmail.ConversationTopic));
						List<MailItem> found = sent.OfType<MailItem>().ToList();

						Logger.LogInfo(string.Format(CultureInfo.CurrentCulture, "EMAILTRACKING: Found {0} sent items matching topic - {1}", found.Count,receivedEmail.ConversationIndex));

						if (found.Count > 0)
						{
							parent = (from a in found
									  where a.SentOn == found.Max(f => f.SentOn)
											&& a.Attachments.Count > 0
									  select a).FirstOrDefault();

							Logger.LogInfo(string.Format(CultureInfo.CurrentCulture,
														  "EMAILTRACKING: Sent Email was {0}Found - {1}",
							                              parent == null ? "NOT " : "",
							                              parent != null ? parent.ConversationTopic : ""));
						}
					}
				}
			}
			catch (COMException ex)
			{
				// More then likely we can't find the original message sent by us or
				// we have Received an email with attachments that is not a reply!
				Logger.LogInfo("EMAILTRACKING: Exception was raised! " + ex.Message);
			}

			return parent;
		}
        /// <summary>
        /// Signs the given mail item, if possible, according to the DKIM standard.
        /// </summary>
        /// <param name="mailItem">The mail item that is to be signed, if possible.</param>
        private void SignMailItem(MailItem mailItem)
        {
            // If the mail item is a "system message" then it will be read-only here,
            // and we can't sign it. Additionally, if the message has a "TnefPart",
            // then it is in a proprietary format used by Outlook and Exchange Server,
            // which means we shouldn't bother signing it.

            if (!mailItem.Message.IsSystemMessage &&
                mailItem.Message.TnefPart == null)
            {
                using (var inputStream = mailItem.GetMimeReadStream())
                {
                    string dkim = this.dkimSigner.CanSign(inputStream);

                    if (dkim.Length != 0)
                    {
                        Logger.LogInformation("Signing mail with header: " + dkim);

                        inputStream.Seek(0, SeekOrigin.Begin);
                        byte[] inputBuffer = ReadFully(inputStream);
                        inputStream.Close();

                        using (var outputStream = mailItem.GetMimeWriteStream())
                        {
                            try
                            {
                                this.dkimSigner.Sign(inputBuffer, outputStream, dkim);
                            }
                            catch (Exception ex)
                            {
                                Logger.LogError("Signing went terribly wrong: " + ex.ToString());
                            }

                            outputStream.Close();
                        }

                    }
                }
            }
        }
		private List<string> ResolveEmailAddresses(MailItem mailItem)
		{
			var emailAddresses = new List<string>();
			var recipients = mailItem.Recipients;
			using (new ComRelease(recipients))
			{
				recipients.ResolveAll();
				for (int i = 1; i <= recipients.Count; i++)
				{
					var recipient = recipients[i];
					using (new ComRelease(recipient))
					{
						var addressEntry = recipient.AddressEntry;
						using (new ComRelease(addressEntry))
						{
							emailAddresses.AddRange(ResolveAddressEntry(addressEntry));
						}
					}
				}
				return emailAddresses;
			}
		}
Example #60
0
		protected override IEnumerable<string> GetListofRecordKeys(MailItem mailItem, MessageBodyFormat bodyFormat)
		{
			var recordKeys = new List<string>();
			try
			{
				for (int i = 1; i <= mailItem.Attachments.Count; i++)
				{
					if (!OomSignatureInspector.IsSignature(mailItem.Attachments[i], bodyFormat))
					{
					    dynamic attachment = mailItem.Attachments[i];
                        recordKeys.Add(attachment.RecordKey);
					}
				}
			}
			catch (Exception ex)
			{
				Interop.Logging.Logger.LogError(ex);
				throw;
			}

			return recordKeys;
		}