public OutlookEmailSender2() { Outlook.Application olApplication = new Outlook.Application(); Outlook.NameSpace olNameSpace = olApplication.GetNamespace("mapi"); olNameSpace.Logon(Type.Missing, Type.Missing, true, true); olMailItem = (Outlook.MailItem)olApplication.CreateItem(Outlook.OlItemType.olMailItem); olRecipients = olMailItem.Recipients; olApplication.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(olApplication_ItemSend); }
public OutlookRecipientTableProxy(MSOutlook.MailItem outlookmail, bool bUseCache) { if (null == outlookmail) throw new ArgumentNullException("OutlookMail"); m_bUseCache = bUseCache; m_outlookmail = outlookmail ; m_outlookmail.Recipients.ResolveAll(); Logger.LogDebug("OutlookRecipientTableProxy::GetRecipients ResolveAll Completed"); }
public EmailObject(String attachmentPath, String bodyPath, String addressString, String subject) { // Create stuff for Outlook outlookApp = new OutlookApp(); mailItem = outlookApp.CreateItem(Outlook.OlItemType.olMailItem); // Create sender - necessary? Outlook.AddressEntry currentUser = outlookApp.Session.CurrentUser.AddressEntry; // Create the email object we are going to use constructEmailObject(attachmentPath, bodyPath, addressString, subject); }
private void Dispose(bool disposing) { if (m_disposed) return; m_disposed = true; if (disposing) { } if (null != m_mailItem) { Marshal.ReleaseComObject(m_mailItem); m_mailItem = null; } }
private void Dispose(bool disposing) { if (m_Disposed) return; m_Disposed = true; if (disposing) { } if (m_outlookAttachmentsProxy != null) { m_outlookAttachmentsProxy.Dispose(); m_outlookAttachmentsProxy = null; } m_outlookMail = null; }
private void CreateFromTemplate(string filename) { Outlook.MAPIFolder drafts = null; Outlook.Application application = null; try { drafts = m_outlookSession.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderDrafts); application = m_outlookSession.Application; m_mailItem = application.CreateItemFromTemplate(filename, drafts); if (null == m_mailItem) throw new ArgumentNullException("m_mailItem"); } finally { if (null != drafts) Marshal.ReleaseComObject(drafts); if (null != application) Marshal.ReleaseComObject(application); } }
private void Initialise(object mailItem, bool bUseCache, bool disableAccessToDOMAttachments) { if (null == mailItem) throw new ArgumentNullException("mailItem"); m_outlookMail = mailItem as MSOutlook.MailItem; if (null == m_outlookMail) throw new ArgumentNullException("m_outlookMail"); m_oif = new OutlookIImplFactory(); m_mailItem = m_oif.CreateWSMail(m_outlookMail); m_outlookRecipientTableProxy = new RedemptionRecipientTableProxy(m_outlookMail, bUseCache); m_outlookToRecipientsProxy = new RedemptionRecipientsProxy(m_outlookRecipientTableProxy, OutlookRecipientTypes.ToRecipient); m_outlookCcRecipientsProxy = new RedemptionRecipientsProxy(m_outlookRecipientTableProxy, OutlookRecipientTypes.CcRecipient); m_outlookBccRecipientsProxy = new RedemptionRecipientsProxy(m_outlookRecipientTableProxy, OutlookRecipientTypes.BccRecipient); m_outlookAttachmentsProxy = new RedemptionAttachmentsProxy(m_outlookMail, disableAccessToDOMAttachments); m_bIsValid = true; }
void Application_ItemContextMenuDisplay(Office.CommandBar CommandBar, Outlook.Selection Selection) { if (Selection.Count > 0) { mail = Selection[1] as Outlook.MailItem; if (mail != null) { btnID = CommandBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, missing, missing) as Office.CommandBarButton; btnID.Style = Microsoft.Office.Core.MsoButtonStyle.msoButtonIconAndCaption; btnID.Caption = "Copy Email ID"; btnID.FaceId = 224; btnID.Click += new Office._CommandBarButtonEvents_ClickEventHandler(btn_CopyEmailID); btnNotes = CommandBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, missing, missing) as Office.CommandBarButton; btnNotes.Style = Microsoft.Office.Core.MsoButtonStyle.msoButtonIconAndCaption; btnNotes.Caption = "Email Notes..."; btnNotes.FaceId = 1996; btnNotes.Click += new Office._CommandBarButtonEvents_ClickEventHandler(btn_EmailNotes); } } }
private void CopyBody(ref AppointmentItem ai, MailItem mailItem) { ThisAddIn.g_log.Info("Copy AppointmentItem body to MailItem enter"); Word.Document Doc = new Word.Document(); Word.Document Doc2 = new Word.Document(); //Doc = Globals.ThisAddIn.Application.ActiveInspector().WordEditor as Word.Document; Doc = ai.GetInspector.WordEditor as Word.Document; //Doc = g_currentAppointItem.GetInspector.WordEditor as Word.Document; if (Doc != null) { ThisAddIn.g_log.Info(string.Format("appointmentItem doc length is {0}.", Doc.Content.Text.Length)); Doc.Activate(); Doc.Select(); //App1 = Doc.Windows.Application; //Sel = App1.Selection; //Sel.WholeStory(); //Sel.Copy(); Doc.Range().WholeStory(); Doc.Range().Copy(); Doc2 = mailItem.GetInspector.WordEditor as Word.Document; if (Doc2 != null) { Doc2.Activate(); object start = 0; Range newRang = Doc2.Range(ref start, ref start); int ioo = Doc2.Sections.Count; Section sec = Doc2.Sections[1]; sec.Range.InsertBreak(Type.Missing);//插入换行符 try { //sec.Range.PasteAndFormat(WdRecoveryType.wdPasteDefault); sec.Range.PasteAndFormat(WdRecoveryType.wdFormatOriginalFormatting); mailItem.Save(); ThisAddIn.g_log.Info(string.Format("mailItem doc length is {0}.", Doc2.Content.Text.Length)); if (mailItem.Body == null || mailItem.Body.Length < 100) { Doc2.Activate(); ((_Inspector)(mailItem.GetInspector)).Activate(); ThisAddIn.g_log.Info("mailItem's body is null Or body length is short,Activate over"); } } catch (System.Exception ex) { ThisAddIn.g_log.Info("CopyBody comes Exception: " + ex.ToString()); } } } if (Doc != null) { Marshal.ReleaseComObject(Doc); Doc = null; } if (Doc2 != null) { Marshal.ReleaseComObject(Doc2); Doc2 = null; } ThisAddIn.g_log.Info("Copy AppointmentItem body to MailItem exit"); }
public void ProcessFolder(Outlook.MAPIFolder folder) { DataTable messagesDt = app.OutlookDataSet.Tables["messages"]; foreach (object obj in folder.Items) { if ((obj as Outlook.MailItem) == null) { continue; } Outlook.MailItem message = obj as Outlook.MailItem; if (message == null) { continue; } if (messagesDt.Rows.Count > app.MaxRecords) { break; } bool addMessage = true; if (app.EntryId != null && app.EntryId.Length > 0) { if (message.EntryID.ToLower() != app.EntryId.ToLower()) { addMessage = false; } } else { if (message.Subject != null) { if (app.SubjectContains != null && app.SubjectContains.Length > 0 && !message.Subject.ToLower().Contains(app.SubjectContains.ToLower())) { addMessage = false; } if (app.SubjectContainsRegex != null && app.SubjectContainsRegex.Length > 0) { Match m = Regex.Match(message.Subject, app.SubjectContainsRegex); if (!m.Success) { addMessage = false; } } } else { addMessage = false; } if (message.Body != null) { if (app.BodyContains != null && app.BodyContains.Length > 0 && !message.Body.ToLower().Contains(app.BodyContains.ToLower())) { addMessage = false; } if (app.BodyContainsRegex != null && app.BodyContainsRegex.Length > 0) { Match m = Regex.Match(message.Body, app.BodyContainsRegex); if (!m.Success) { addMessage = false; } } } else { addMessage = false; } } if (addMessage) { string headers = message.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E"); List <string> recipientList = new List <string>(); foreach (Outlook.Recipient recipient in message.Recipients) { recipientList.Add(recipient.Address); Utils.AddEmailAddressRow(app, recipient.Address, recipient.Name); } Utils.AddEmailAddressRow(app, message.SenderEmailAddress, ""); Utils.AddEmailAddressRow(app, message.CC, ""); Utils.AddMessageRow(app, message.EntryID, string.Join(";", recipientList.ToArray()), message.Sender.Address, message.CC, headers, message.ReceivedTime.ToString(), message.Subject, message.Body, message.HTMLBody, Encoding.UTF8.GetString(message.RTFBody), message.Size, message.Attachments.Count); if (message.Attachments.Count > 0) { for (int a = 0; a < message.Attachments.Count; a++) { Outlook.Attachment attachment = message.Attachments[a + 1]; //not zero-based Utils.AddAttachmentRow(app, message.EntryID, attachment.FileName, attachment.PathName, attachment.Size, attachment.DisplayName); } } } } if (folder.Folders.Count > 0) { foreach (Outlook.MAPIFolder f in folder.Folders) { ProcessFolder(f); } } }
/// <summary> /// code written by Joy /// excutes ansd the start the timer upload process when the backgoundworkers's do work event fires /// </summary> /// <param name="Item"></param> void doBackGroundUpload(object Item) { try { Globals.ThisAddIn.isTimerUploadRunning = true; OutlookObj = Globals.ThisAddIn.Application; outlookNameSpace = OutlookObj.GetNamespace("MAPI"); Outlook.MAPIFolder oInBox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); Outlook.MAPIFolder olMailRootFolder = (Outlook.MAPIFolder)oInBox.Parent; oMailRootFolders = olMailRootFolder.Folders; Outlook.MailItem moveMail = (Outlook.MailItem)Item; string newCatName = "Successfully Uploaded"; if (Globals.ThisAddIn.Application.Session.Categories[newCatName] == null) { outlookNameSpace.Categories.Add(newCatName, Outlook.OlCategoryColor.olCategoryColorDarkGreen, Outlook.OlCategoryShortcutKey.olCategoryShortcutKeyNone); } XmlNode uploadFolderNode = UserLogManagerUtility.GetSPSiteURLDetails("", folderName); if (uploadFolderNode != null) { bool isDroppedItemUplaoded = false; addinExplorer = ThisAddIn.OutlookObj.ActiveExplorer(); //Check the folder mapping with documnet library if (isUserDroppedItemsCanUpload == false) { //Show message try { Outlook.MailItem m = (Outlook.MailItem)Item; mailitemEntryID = m.EntryID; try { mailitem = m; mailitemEntryID = m.EntryID; string strsubject = m.EntryID; if (string.IsNullOrEmpty(strsubject)) { strsubject = "tempomailcopy"; } mailitemEntryID = strsubject; string tempFilePath = UserLogManagerUtility.RootDirectory + "\\" + strsubject + ".msg"; if (Directory.Exists(UserLogManagerUtility.RootDirectory) == false) { Directory.CreateDirectory(UserLogManagerUtility.RootDirectory); } m.SaveAs(tempFilePath, Outlook.OlSaveAsType.olMSG); } catch (Exception ex) { } Outlook.MAPIFolder fp = (Outlook.MAPIFolder)m.Parent; DoNotMoveInNonDocLib(mailitemEntryID, fp); } catch (Exception) { NonDocMoveReportItem(Item); } MessageBox.Show("You are attempting to move files to a non document library. This action is not supported.", "ITOPIA", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (frmUploadItemsListObject == null || (frmUploadItemsListObject != null && frmUploadItemsListObject.IsDisposed == true)) { //frmUploadItemsListObject = new frmUploadItemsList(); // myCustomTaskPane = Globals.ThisAddIn.CustomTaskPanes.Add(frmUploadItemsListObject, "ITOPIA"); //myCustomTaskPane.Visible = true; IAddCustomTaskPane(); } //frmUploadItemsListObject.TopLevel = true; //frmUploadItemsListObject.TopMost = true; ////////////////////// frmUploadItemsListObject.Show(); try { ////// ////////// Outlook.MailItem oMailItem = (Outlook.MailItem)Item; parentfolder = (Outlook.MAPIFolder)oMailItem.Parent; try { mailitem = oMailItem; mailitemEntryID = oMailItem.EntryID; string strsubject = oMailItem.EntryID; if (string.IsNullOrEmpty(strsubject)) { strsubject = "tempomailcopy"; } mailitemEntryID = strsubject; string tempFilePath = UserLogManagerUtility.RootDirectory + "\\" + strsubject + ".msg"; if (Directory.Exists(UserLogManagerUtility.RootDirectory) == false) { Directory.CreateDirectory(UserLogManagerUtility.RootDirectory); } oMailItem.SaveAs(tempFilePath, Outlook.OlSaveAsType.olMSG); } catch (Exception ex) { } string fileName = string.Empty; if (!string.IsNullOrEmpty(oMailItem.Subject)) { //Replce any specila characters in subject fileName = Regex.Replace(oMailItem.Subject, strMailSubjectReplcePattern, " "); fileName = fileName.Replace(".", "_"); } if (string.IsNullOrEmpty(fileName)) { DateTime dtReceivedDate = Convert.ToDateTime(oMailItem.ReceivedTime); fileName = "Untitled_" + dtReceivedDate.Day + "_" + dtReceivedDate.Month + "_" + dtReceivedDate.Year + "_" + dtReceivedDate.Hour + "_" + dtReceivedDate.Minute + "_" + dtReceivedDate.Millisecond; } UploadItemsData newUploadData = new UploadItemsData(); newUploadData.ElapsedTime = DateTime.Now; newUploadData.UploadFileName = fileName;// oMailItem.Subject; newUploadData.UploadFileExtension = ".msg"; newUploadData.UploadingMailItem = oMailItem; newUploadData.UploadType = TypeOfUploading.Mail; newUploadData.DisplayFolderName = folderName; frmUploadItemsListObject.UploadUsingDelegate(newUploadData); //Set dropped items is uploaded /////////////////////////updated by Joy on 25.07.2012///////////////////////////////// bool uploadStatus = frmUploadItemsListObject.IsSuccessfullyUploaded; XMLLogOptions userOption = UserLogManagerUtility.GetUserConfigurationOptions(); if (uploadStatus == true) { // Globals.ThisAddIn.isTimerUploaded = true; isDroppedItemUplaoded = true; for (int i = 0; i <= activeDroppingFolder.Items.Count; i++) { try { Outlook.MailItem me = (Outlook.MailItem)activeDroppingFolder.Items[i]; if (me.EntryID == mailitemEntryID) { me.Categories.Remove(0); me.Categories = newCatName; me.Save(); if (userOption.AutoDeleteEmails == true) { UserMailDeleteOption(mailitemEntryID, parentfolder); } } } catch (Exception ex) { } } frmUploadItemsListObject.lblPRStatus.Invoke(new updateProgresStatus(() => { frmUploadItemsListObject.lblPRStatus.Text = Globals.ThisAddIn.no_of_t_item_uploaded.ToString() + " " + "of" + " " + Globals.ThisAddIn.no_of_pending_items_to_be_uploaded.ToString() + " " + "Uploaded"; })); frmUploadItemsListObject.progressBar1.Invoke(new updateProgessBar(() => { frmUploadItemsListObject.progressBar1.Value = (((Globals.ThisAddIn.no_of_t_item_uploaded * 100 / Globals.ThisAddIn.no_of_pending_items_to_be_uploaded))); })); } else { isDroppedItemUplaoded = false; } /////////////////////////updated by Joy on 25.07.2012///////////////////////////////// } catch (Exception ex) { isDroppedItemUplaoded = MoveItemIsReportItem(Item); } try { if (isDroppedItemUplaoded == false) { //string tempName = oDocItem.Subject; string tempName = string.Empty; Outlook.DocumentItem oDocItem = (Outlook.DocumentItem)Item; try { Outlook._MailItem myMailItem = (Outlook.MailItem)addinExplorer.Selection[1]; foreach (Outlook.Attachment oAttachment in myMailItem.Attachments) { if (oAttachment.FileName == oDocItem.Subject) { tempName = oAttachment.FileName; tempName = tempName.Substring(tempName.LastIndexOf(".")); oAttachment.SaveAsFile(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName); //Read file data to bytes //byte[] fileBytes = File.ReadAllBytes(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName); System.IO.FileStream Strm = new System.IO.FileStream(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader reader = new System.IO.BinaryReader(Strm); byte[] fileBytes = reader.ReadBytes(Convert.ToInt32(Strm.Length)); reader.Close(); Strm.Close(); //Replace any special characters are there in file name string fileName = Regex.Replace(oAttachment.FileName, strAttachmentReplacePattern, " "); //Add uplaod attachment item data to from list. UploadItemsData newUploadData = new UploadItemsData(); newUploadData.UploadType = TypeOfUploading.Attachment; newUploadData.AttachmentData = fileBytes; newUploadData.DisplayFolderName = activeDroppingFolder.Name; if (fileName.Contains(".")) { newUploadData.UploadFileName = fileName.Substring(0, fileName.LastIndexOf(".")); newUploadData.UploadFileExtension = fileName.Substring(fileName.LastIndexOf(".")); if (string.IsNullOrEmpty(newUploadData.UploadFileName.Trim())) { //check file name conatins empty add the date time newUploadData.UploadFileName = "Untitled_" + DateTime.Now.ToFileTime(); } } //Add to form frmUploadItemsListObject.UploadUsingDelegate(newUploadData); //Set dropped mail attachment items is uploaded. isDroppedItemUplaoded = true; newUploadData = null; //oDocItem.Delete(); break; } } } catch (InvalidCastException ex) { //Set dropped mail attachment items is uploaded to false isDroppedItemUplaoded = false; } if (isDroppedItemUplaoded == false) { tempName = oDocItem.Subject; tempName = tempName.Substring(tempName.LastIndexOf(".")); oDocItem.SaveAs(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName, Type.Missing); System.IO.FileStream Strm = new System.IO.FileStream(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader reader = new System.IO.BinaryReader(Strm); byte[] fileBytes = reader.ReadBytes(Convert.ToInt32(Strm.Length)); reader.Close(); Strm.Close(); //Replace any special characters are there in file name string fileName = Regex.Replace(oDocItem.Subject, strAttachmentReplacePattern, " "); //Add uplaod attachment item data to from list. UploadItemsData newUploadData = new UploadItemsData(); newUploadData.UploadType = TypeOfUploading.Attachment; newUploadData.AttachmentData = fileBytes; newUploadData.DisplayFolderName = activeDroppingFolder.Name; if (fileName.Contains(".")) { newUploadData.UploadFileName = fileName.Substring(0, fileName.LastIndexOf(".")); newUploadData.UploadFileExtension = fileName.Substring(fileName.LastIndexOf(".")); if (string.IsNullOrEmpty(newUploadData.UploadFileName.Trim())) { //check file name conatins empty add the date time newUploadData.UploadFileName = "Untitled_" + DateTime.Now.ToFileTime(); } } //Add to form frmUploadItemsListObject.UploadUsingDelegate(newUploadData); newUploadData = null; //oDocItem.Delete(); } } } catch (Exception ex) { //throw ex; //////////////////////////////updated by Joy on 28.07.2012/////////////////////////////////// // EncodingAndDecoding.ShowMessageBox("FolderItem Add Event_DocItem Conv", ex.Message, MessageBoxIcon.Error); //////////////////////////////updated by Joy on 28.07.2012/////////////////////////////////// } try { XMLLogOptions userOptions = UserLogManagerUtility.GetUserConfigurationOptions(); for (int i = 0; i <= parentfolder.Items.Count; i++) { try { Outlook.MailItem me = (Outlook.MailItem)parentfolder.Items[i]; if (me.EntryID == mailitemEntryID) { ///////////////////////////modified by Joy on 10.08.2012//////////////////////////////////// if (isDroppedItemUplaoded == true) { me.Categories.Remove(0); me.Categories = newCatName; me.Save(); if (userOptions.AutoDeleteEmails == true) { UserMailDeleteOption(mailitemEntryID, parentfolder); } //parentfolder.Items.Remove(i); } ///////////////////////////modified by Joy on 10.08.2012//////////////////////////////////// } } catch (Exception) { } } } catch (Exception) { } if (!string.IsNullOrEmpty(mailitemEntryID)) { if (ItemType == TypeOfMailItem.ReportItem) { UserReportItemDeleteOption(mailitemEntryID, parentfolder); } else { ///////////////////////////Updated by Joy on 16.08.2012....to be updated later/////////////////////////////// // UserMailDeleteOption(mailitemEntryID, parentfolder); ///////////////////////////Updated by Joy on 16.08.2012....to be updated later/////////////////////////////// } } } } catch (Exception ex) { EncodingAndDecoding.ShowMessageBox("Folder Item Add Event", ex.Message, MessageBoxIcon.Error); } //AddToUploadList(Item); }
private void Tagline() { Outlook.Inspector inspector = this.Context as Outlook.Inspector; Outlook.MailItem mi = inspector.CurrentItem as Outlook.MailItem; msgBody.updateTask(mi, taglineActive); // update the message body based on the value of taglineActive }
// e메일 업데이트 - 크래쉬 덤프 첨부 파일 찾아서 파싱 void UpdateMail() { Outlook.MAPIFolder selectedFolder = folder; Outlook.Items items = folder.Items; parselist.Clear(); int iEmailItemSize = items.Count; System.Diagnostics.Process process; System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(); System.Collections.ArrayList updatelist = new ArrayList(); System.Collections.ArrayList deletelist = new ArrayList(); this.progressBar1.Maximum = iEmailItemSize; this.label3.Text = ""; this.label2.Text = "다운로드 && 분석"; this.progressBar2.Value = 0; for (int iIdx = 1; iIdx <= iEmailItemSize; iIdx++) { try { Outlook.MailItem msg = (Outlook.MailItem)items[iIdx]; string msgDate = string.Format("{0:yyyy/MM/dd}", msg.CreationTime); string hackUser = msg.Subject.Substring(0, msg.Subject.IndexOf("님")); string [] str = selectedFolder.FolderPath.Split('\\'); string version = str[str.Length - 1]; updatelist.Add(iIdx); if (parselist.Contains(version) == false) { parselist.Add(version, 0); } } catch (System.Exception e) { e.ToString(); } this.progressBar1.Value = iIdx; this.label1.Text = string.Format("리스트 업데이트 ({0}/{1})", this.progressBar1.Value, this.progressBar1.Maximum); } this.progressBar2.Maximum = updatelist.Count; this.progressBar2.Value = 0; System.Collections.ArrayList ProcessName = new ArrayList(); int nProcess = 0; foreach (int i in updatelist) { lock ( thread ) { Outlook.MailItem msg = (Outlook.MailItem)items[i]; ProcessName.Clear(); if (msg != null) { try { string time = string.Format("{0:yyyy/MM/dd}", msg.CreationTime); string hackUser = msg.Subject.Substring(0, msg.Subject.IndexOf("님")); string [] str = selectedFolder.FolderPath.Split('\\'); string version = str[str.Length - 1]; int nCount = 0; char[] ch = { '\r' }; string msgBody = msg.Body; msgBody = msgBody.Replace("\r\n", "\r"); string[] bodyArray = msgBody.Split(ch); nCount = bodyArray.GetLength(0); // 버전 폴더 생성 if (System.IO.Directory.Exists("HackUser\\" + version) == false) { System.IO.Directory.CreateDirectory("HackUser\\" + version); } // 버전 폴더 생성 if (System.IO.Directory.Exists("HackUser\\" + version + "\\" + hackUser) == false) { System.IO.Directory.CreateDirectory("HackUser\\" + version + "\\" + hackUser); } this.label3.Text = version + " " + hackUser; string filename = System.Windows.Forms.Application.StartupPath + "\\HackUser\\" + version + "\\" + hackUser + "\\dmp.txt"; nProcess = 0; if (System.IO.File.Exists(filename) == true) { System.IO.StreamReader reader = new System.IO.StreamReader(filename, System.Text.Encoding.Default); while (reader.Peek() > 0) { string strData = reader.ReadLine(); ProcessName.Add(strData); ++nProcess; } reader.Close(); } bool bFind; for (int index1 = 0; index1 < nCount; ++index1) { bFind = false; for (int index2 = 0; index2 < nProcess; ++index2) { if (ProcessName[index2].Equals(bodyArray[index1]) == true) { bFind = true; break; } } if (bFind == false) { ProcessName.Add(bodyArray[index1]); ++nProcess; } } System.IO.StreamWriter fsw = System.IO.File.CreateText(filename); string temp = "[" + hackUser + "]"; if (nCount == 0 || temp.Equals(ProcessName[0]) == false) { fsw.Write("[" + hackUser + "]\r\n\r\n"); } for (int index3 = 0; index3 < nProcess; ++index3) { fsw.Write(ProcessName[index3] + "\r\n"); } fsw.Flush(); fsw.Close(); //}} dmlee 2008.05.25 메일 제목과 본문 내용 출력 // fix!! state.log, error.log의 끝에 10줄 정도를 같이 출력하자 // 크래쉬 덤프 텍스트 파싱 FormattingLog(System.Windows.Forms.Application.StartupPath + "\\HackUser\\" + version + "\\" + hackUser + "\\dmp.txt"); //System.IO.File.Delete( "HackUser\\"+version+"\\"+time+"\\dmp.txt" ); // fix!! 메일 제목과 본문내용을 보기위해 지우지 말고 남겨둠 } catch (System.Exception e) { MessageBox.Show(e.ToString()); continue; } } } this.progressBar2.Value++; this.label2.Text = string.Format("다운로드 && 분석 ({0}/{1})", this.progressBar2.Value, this.progressBar2.Maximum); } this.label3.Text = ""; thread = null; this.DialogResult = DialogResult.OK; }
void _inspectors_NewInspector(Outlook.Inspector Inspector) { if (Inspector == null) throw new ArgumentNullException("Inspector is null"); theCurrentMailItem = null; object item = Inspector.CurrentItem; if (item == null) return; if (!(item is Outlook.MailItem)) return; theCurrentMailItem = Inspector.CurrentItem as Outlook.MailItem; theCurrentMailItem.Open += theCurrentMailItem_Open; ThisAddIn.bPeppermintMessageInserted = false; }
public bool EnviarEmail() { if (CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVl_BoolTerminal("ST_ENVIAR_EMAIL_OUTLOOK", Utils.Parametros.pubTerminal, null)) { if (Destinatario.Count > 0) { try { if (System.Diagnostics.Process.GetProcessesByName("OUTLOOK").Count().Equals(0)) { System.Diagnostics.ProcessStartInfo inf = new System.Diagnostics.ProcessStartInfo("OUTLOOK"); inf.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized; System.Diagnostics.Process.Start(inf); } OutLook.Application oApp = new Microsoft.Office.Interop.Outlook.Application(); OutLook.MailItem oMsg = oApp.CreateItem(OlItemType.olMailItem) as OutLook.MailItem; //Titulo do email oMsg.Subject = Titulo.Trim(); //Assinatura do usuário object usu = new CamadaDados.Diversos.TCD_CadUsuario().BuscarEscalar( new Utils.TpBusca[] { new Utils.TpBusca() { vNM_Campo = "a.login", vOperador = "=", vVL_Busca = "'" + Utils.Parametros.pubLogin.Trim() + "'" } }, "a.nome_usuario"); if (usu != null && !string.IsNullOrEmpty(usu.ToString())) { Mensagem = Mensagem.Trim() + "\n\n\n Ass.: " + usu; } //Mensagem do email oMsg.HTMLBody = Mensagem.Trim(); if (Anexo.Count > 0) { int posicao = oMsg.Body.Length + 1; int iAnexo = Convert.ToInt32(OutLook.OlAttachmentType.olByValue); int cont = 1; foreach (string a in Anexo) { oMsg.Attachments.Add(a, iAnexo, posicao, "Anexo" + (cont++).ToString()); } } //Destinatario OutLook.Recipients r = oMsg.Recipients; foreach (string d in Destinatario) { OutLook.Recipient oR = r.Add(d); oR.Resolve(); } //Enviar email oMsg.Send(); return(true); } catch (System.Exception ex) { MessageBox.Show("Erro enviar email: " + ex.Message.Trim(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } } else { return(false); } } else { //Objeto Email System.Net.Mail.MailMessage objemail = new System.Net.Mail.MailMessage(); //Remetente do Email Remetente = CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVlString("EMAIL_PADRAO", null).Trim().ToLower(); if (string.IsNullOrEmpty(Remetente)) { MessageBox.Show("Não existe email padrão configurado.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } if (CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVL_Bool("ST_COPIA_EMAIL", string.Empty, null).Trim().ToUpper().Equals("S")) { object obj = new CamadaDados.Diversos.TCD_CadUsuario().BuscarEscalar( new Utils.TpBusca[] { new Utils.TpBusca() { vNM_Campo = "a.login", vOperador = "=", vVL_Busca = "'" + Utils.Parametros.pubLogin.Trim() + "'" } }, "a.email_padrao"); if (obj != null) { objemail.Bcc.Add(obj.ToString()); } } objemail.From = new System.Net.Mail.MailAddress(Remetente.Trim().ToLower()); //Destinatario do Email if (Destinatario.Count < 1) { MessageBox.Show("Obrigatorio informar destinatario para enviar email.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } foreach (string d in Destinatario) { objemail.To.Add(new System.Net.Mail.MailAddress(d.Trim().ToLower())); } //Titulo do Email if (Titulo.Trim().Equals(string.Empty)) { MessageBox.Show("Obrigatorio informar titulo para enviar email.", "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } objemail.Subject = Titulo.Trim(); //Assinatura do usuário object usu = new CamadaDados.Diversos.TCD_CadUsuario().BuscarEscalar( new Utils.TpBusca[] { new Utils.TpBusca() { vNM_Campo = "a.login", vOperador = "=", vVL_Busca = "'" + Utils.Parametros.pubLogin.Trim() + "'" } }, "a.nome_usuario"); if (usu != null && !string.IsNullOrEmpty(usu.ToString())) { Mensagem = Mensagem.Trim() + "\n\n\n Ass.: " + usu; } //Mensagem do Email objemail.Body = Mensagem.Trim(); //Html objemail.IsBodyHtml = St_html; //Anexos do email foreach (string str in Anexo) { objemail.Attachments.Add(new System.Net.Mail.Attachment(str.Trim())); } //Configurar objeto SMTP Smtp = CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVlString("SERVIDOR_SMTP", Utils.Parametros.pubTerminal, null); if (Smtp.Trim().Equals(string.Empty)) { MessageBox.Show("Não existe configuração de servidor smtp para o terminal " + Utils.Parametros.pubTerminal.Trim(), "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } System.Net.Mail.SmtpClient objsmtp = new System.Net.Mail.SmtpClient(); if (CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVlBool("CONEXAO_SSL_SMTP", null)) { objsmtp.EnableSsl = true; } objsmtp.Credentials = new System.Net.NetworkCredential(CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVlString("EMAIL_PADRAO", null).Trim().ToLower(), CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVlString("SENHA_EMAIL", null).Trim().ToLower()); objsmtp.Host = Smtp.Trim().ToLower(); //Configurar porta smtp Porta_smtp = Convert.ToInt32(CamadaNegocio.ConfigGer.TCN_CadParamGer.BuscaVlNumerico("PORTA_SMTP", Utils.Parametros.pubTerminal, null)); if (Porta_smtp < 1) { MessageBox.Show("Não existe configuração de porta smtp para o terminal " + Utils.Parametros.pubTerminal.Trim(), "Mensagem", MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } objsmtp.Port = Porta_smtp; //Criar metodo email enviado objsmtp.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(objsmtp_SendCompleted); //Enviar Email try { objsmtp.SendAsync(objemail, "Email enviado com sucesso"); return(true); } catch (System.Exception ex) { throw new System.Exception("Erro enviar email: " + ex.Message.Trim()); } finally { objsmtp = null; } } }
private void Create() { Outlook.MAPIFolder drafts = null; Outlook.Items items = null; try { drafts = m_outlookSession.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts); items = drafts.Items; m_mailItem = items.Add(0); if (null == m_mailItem) throw new ArgumentNullException("m_mailItem"); } finally { if (null != items) Marshal.ReleaseComObject(items); if (null != drafts) Marshal.ReleaseComObject(drafts); } }
private static void MailParser(Outlook.MailItem mail) { #region E-Mail Filter /// <summary> /// Creates a list read from text file of e-mail addresses of senders, later if the sender is on this list the program will do stuff else it will ignore e-mail. /// </summary> List <string> filter = new List <string>(); //New list to hold e-mail addresses to check try { if (File.Exists(@"c:\User Programs\filter.txt")) //populates the list if the text file exists { using (StreamReader sr = new StreamReader(@"c:\User Programs\filter.txt")) // the streamreader will auto close the text file when done reading. { while (sr.Peek() >= 0) //reads until the end of the file, peek checks the next line for content. { filter.Add(sr.ReadLine()); } } } else //If the text file didn't exist asks the user to create one { MessageBox.Show(@"Please define a text file at C:\User Programs\filter.txt insert salesman names you'd like to run manifold program for one on each line"); } } catch { } #endregion bool tester = filter.Any(name => mail.SenderEmailAddress.ToUpper().Contains(name.ToUpper())); //Create a bool object to check if the mail sender is one of the names in the filter file if (tester) //If the sender is one of the filter names then continue more checks, otherwise will ignore the e-mail { try { var attachments = mail.Attachments; //Pull out the attachments to read pdf sales orders var attachmentMatches = new List <string>(); if (attachments.Count > 0) { string tempPdf = System.IO.Path.GetTempFileName(); for (int i = 1; i <= mail.Attachments.Count; i++) { if (mail.Attachments[i].FileName.Contains(".pdf")) { mail.Attachments[i].SaveAsFile(tempPdf); List <string> tempAttachments = Attachment(tempPdf); if (tempAttachments.Count > 0) { attachmentMatches.AddRange(tempAttachments); } } } File.Delete(tempPdf); } // Find manifold PN's in the e-mail body with regular expressions MatchCollection matches = Regex.Matches(mail.Body, @"\d\d?\w+-\d\d?-.+?(?=\s)", RegexOptions.IgnoreCase); // was having problem with passing matches so change to string string[] output = new string[attachmentMatches.Count + matches.Count]; if (matches.Count > 0) { for (int i = 0; i < matches.Count; i++) { output[i] = matches[i].ToString(); } } if (attachmentMatches.Count > 0) { for (int i = 0; i < attachmentMatches.Count; i++) { output[i + matches.Count] = attachmentMatches[i]; } } if (output.Count() > 0) { ProcessStartInfo startInfo = new ProcessStartInfo(); // code to pass arguments to manifoldlister. Console menu to open manifolds. startInfo.CreateNoWindow = false; startInfo.UseShellExecute = false; startInfo.FileName = "ManifoldLister.exe"; const string argsSeparator = " "; string args = string.Join(argsSeparator, output); startInfo.Arguments = args; try { Process.Start(startInfo); } catch (Exception) { MessageBox.Show("Was not able to start ManifoldLister.exe"); } } //OpenFolder(output); } catch (Exception) { } } mail.Close(Outlook.OlInspectorClose.olDiscard); GC.Collect(); }
/// <summary> /// アイテムから、宛先(Recipient)のリスト取得する /// </summary> /// <param name="Item">Outlookアイテムオブジェクト</param> /// <param name="type">アイテムの種類</param> /// <param name="IgnoreMeetingResponse">会議招集の返信かどうか</param> /// <returns>Recipientsインスタンス(会議招集の返信や、MailItem,MeetingItem,AppointmentItemでない場合null)</returns> public static List <Outlook.Recipient> GetRecipients(object Item, ref OutlookItemType type, bool IgnoreMeetingResponse = false) { // MailItemの場合 if (Item is Outlook.MailItem) { type = OutlookItemType.Mail; Outlook.MailItem mail = Item as Outlook.MailItem; return(GetRecipientList(mail)); } // MeetingItemの場合 else if (Item is Outlook.MeetingItem) { Outlook.MeetingItem meeting = Item as Outlook.MeetingItem; // 会議招集の返信の場合 // "IPM.Schedule.Meeting.Resp.Neg"; // "IPM.Schedule.Meeting.Resp.Pos"; // "IPM.Schedule.Meeting.Resp.Tent"; if (meeting.MessageClass.Contains("IPM.Schedule.Meeting.Resp.")) { type = OutlookItemType.MeetingResponse; // 会議招集の返信をする場合、宛先確認画面が表示されないようnullを返す if (IgnoreMeetingResponse) { return(null); } else { return(GetRecipientList(meeting)); } } // 会議出席依頼を送信する場合など else { type = OutlookItemType.Meeting; return(GetRecipientList(meeting)); } } // AppointmentItemの場合(編集中/送信されていない状態でトレイにある会議招集メール、開催者が取り消した会議のキャンセル通知(自分承認済み)) else if (Item is Outlook.AppointmentItem) { type = OutlookItemType.Appointment; Outlook.AppointmentItem appointment = Item as Outlook.AppointmentItem; return(GetRecipientList(appointment)); } else if (Item is Outlook.SharingItem) { type = OutlookItemType.Sharing; Outlook.SharingItem sharing = Item as Outlook.SharingItem; return(GetRecipientList(sharing)); } else if (Item is Outlook.ReportItem) { type = OutlookItemType.Report; Outlook.ReportItem report = Item as Outlook.ReportItem; return(GetRecipientList(report)); } else if (Item is Outlook.TaskItem) { return(null); //type = OutlookItemType.Task; //Outlook.TaskItem task = Item as Outlook.TaskItem; //return GetRecipientList(task); } else if (Item is Outlook.TaskRequestItem) { return(null); //type = OutlookItemType.Task; //Outlook.TaskRequestItem taskRequest = Item as Outlook.TaskRequestItem; //return GetRecipientList(taskRequest); } else if (Item is Outlook.TaskRequestAcceptItem) { return(null); //type = OutlookItemType.TaskRequestResponse; //Outlook.TaskRequestAcceptItem taskRequestAccept = Item as Outlook.TaskRequestAcceptItem; //return GetRecipientList(taskRequestAccept); } else if (Item is Outlook.TaskRequestDeclineItem) { return(null); //type = OutlookItemType.TaskRequestResponse; //Outlook.TaskRequestDeclineItem taskRequestDecline = Item as Outlook.TaskRequestDeclineItem; //return GetRecipientList(taskRequestDecline); } throw new NotSupportedException("未対応のOutlook機能です。"); }
public void Dispose() { if (m_outlookmail != null && Marshal.IsComObject(m_outlookmail)) { Marshal.ReleaseComObject(m_outlookmail); m_outlookmail = null; } }
/// <summary> /// BaclkgoroundWorker's DoWork Event runs in background /// code Written by Joy /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void bw_DoWork(object sender, EventArgs e) { if (Globals.ThisAddIn.isMoveRunning == false && Globals.ThisAddIn.isCopyRunninng==false) { Globals.ThisAddIn.isuploadRunning = true; foreach (Object obj in Globals.ThisAddIn.oselection) { if (obj is Outlook.MailItem) { mailitem = (Outlook.MailItem)obj; doUploading(mailitem); } } Globals.ThisAddIn.isuploadRunning = false; } else if (Globals.ThisAddIn.isMoveRunning == true) { foreach (Object obj in Globals.ThisAddIn.moveSelected) { if (obj is Outlook.MailItem) { mailitem = (Outlook.MailItem)obj; doUploading(mailitem); } } Globals.ThisAddIn.isMoveRunning = false; Globals.ThisAddIn.moveSelected = null; Globals.ThisAddIn.isuploadRunning = false; } else if (Globals.ThisAddIn.isCopyRunninng == true) { foreach (Object obj in Globals.ThisAddIn.copySelected) { if (obj is Outlook.MailItem) { mailitem = (Outlook.MailItem)obj; doUploading(mailitem); } } Globals.ThisAddIn.isCopyRunninng = false; Globals.ThisAddIn.copySelected = null; Globals.ThisAddIn.isuploadRunning = false; } }
//This void Application_ItemContextMenuDisplay(Office.CommandBar CommandBar, Outlook.Selection Selection) { selection = Selection; if (GetMessageClass(selection[1])=="IPM.Note" &&selection.Count==1) { item = (Outlook.MailItem)selection[1]; btnCheckForRule = (Office.CommandBarButton)CommandBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, missing); btnCheckForRule.Caption = "CheckRules"; btnCheckForRule.Click += new Office._CommandBarButtonEvents_ClickEventHandler(btnCheckForRule_Click); foreach (Outlook.Rule R in Application.Session.DefaultStore.GetRules()) { Office.CommandBarButton test= (Office.CommandBarButton)CommandBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, missing); test.Caption = @"ADD2RULE: "+R.Name; test.Click += new Office._CommandBarButtonEvents_ClickEventHandler(btnRules_Click); } } }
//This void Application_ContextMenuClose(Outlook.OlContextMenu ContextMenu) { selection = null; item = null; if (btnCheckForRule != null) { btnCheckForRule.Click -= new Office ._CommandBarButtonEvents_ClickEventHandler( btnRules_Click); } btnCheckForRule = null; }
private void IndexAttachmentBtn_Click(object sender, RibbonControlEventArgs e) { Outlook.MailItem email = ThisEmail(); XLOutlook.IndexAttachments(email); }
public async Task <bool> UploadEmail(Outlook.MailItem item, string nodeId, int?count) { try { string name = item.Subject; //List<char> invalidFileNameChars = Path.GetInvalidFileNameChars().ToList(); //invalidFileNameChars.AddRange(Path.GetInvalidPathChars()); //invalidFileNameChars.AddRange(new char[] { '*', '"', '<', '>', '\\', '/', '.','|' }); //var filename = new string(name.Select(ch => invalidFileNameChars.Contains(ch) ? Convert.ToChar(invalidFileNameChars.IndexOf(ch) + 65) : ch).ToArray()); //if (filename.Length > 200) // filename = filename.Substring(0, 200); //filename = filename.Replace(".", ""); //while ((filename.EndsWith(" "))) //{ // filename = filename.Substring(0, filename.Length-1); //} string filename = ClearFileName(name); // Create Folder Nodes node = new Nodes(); string alt = filename + "_" + (count + 1); string folderId = await node.CreateFolder(nodeId, filename, alt); if (string.IsNullOrEmpty(folderId)) { Error = node.Error; return(false); } if (node.UseAlternative) { filename = alt; } // Save Email string messagePath = Option.TempFolder + filename + ".msg"; item.SaveAs(messagePath, Outlook.OlSaveAsType.olMSGUnicode); //Save Attachment List <string> AttachmentList = new List <string>(); foreach (Outlook.Attachment attachment in item.Attachments) { if (attachment.Type != Outlook.OlAttachmentType.olByValue) { continue; } var attachMethod = 0; var attachFlags = 0; string PR_ATTACH_METHOD = "http://schemas.microsoft.com/mapi/proptag/0x37050003"; try { attachMethod = attachment.PropertyAccessor.GetProperty(PR_ATTACH_METHOD); } catch (Exception ex) { // skip } string PR_ATTACH_FLAGS = "http://schemas.microsoft.com/mapi/proptag/0x37140003"; try { attachFlags = attachment.PropertyAccessor.GetProperty(PR_ATTACH_FLAGS); } catch (Exception ex) { // skip } if (item.BodyFormat == Outlook.OlBodyFormat.olFormatHTML) { if (attachFlags == 4) { continue; } } if (item.BodyFormat == Outlook.OlBodyFormat.olFormatRichText) { if (attachMethod == 6) { continue; } } if (item.HTMLBody.Contains("cid:" + attachment.FileName)) { continue; } string path = Option.TempFolder + attachment.FileName; if (path.Length > 245) { path = path.Substring(0, 240) + ".." + Path.GetExtension(attachment.FileName); } attachment.SaveAsFile(path); AttachmentList.Add(path); Marshal.ReleaseComObject(attachment); } // Upload File UploadFile uFile = new UploadFile(); bool isUploaded = await uFile.Upload(folderId, messagePath); Error = uFile.Error; if (isUploaded) { foreach (string attchPath in AttachmentList) { isUploaded = await uFile.Upload(folderId, attchPath); Error = uFile.Error; } } AttachmentList.Add(messagePath); DeleteFolders(AttachmentList); return(isUploaded); } finally { } }
private void CopyBody(AppointmentItem ai, MailItem mailItem) { ThisAddIn.g_log.Info("Copy AppointmentItem body to MailItem enter"); Word.Document Doc = new Word.Document(); Word.Document Doc2 = new Word.Document(); Word.Application App1; Word.Selection Sel; Doc = ai.GetInspector.WordEditor as Word.Document; Word.Application App2; Word.Selection Sel2; if (Doc != null) { ThisAddIn.g_log.Info(string.Format("appointmentItem doc length is {0}.", Doc.Content.Text.Length)); Doc.Activate(); Doc.Select(); App1 = Doc.Windows.Application; Sel = App1.Selection; Sel.WholeStory(); Sel.Copy(); Doc2 = mailItem.GetInspector.WordEditor as Word.Document; if (Doc2 != null) { Doc2.Activate(); Doc2.Select(); App2 = Doc2.Windows.Application; Sel2 = App2.Selection; Sel2.WholeStory(); try { Sel2.PasteAndFormat(WdRecoveryType.wdPasteDefault); } catch (System.Exception ex) { ThisAddIn.g_log.Error(string.Format("copy to body exception, {0}", ex.ToString())); } mailItem.Save(); ThisAddIn.g_log.Info(string.Format("mailItem doc length is {0}.", Doc2.Content.Text.Length)); if (mailItem.Body == null || mailItem.Body.Length < 100) { Doc2.Activate(); ((_Inspector)(mailItem.GetInspector)).Activate(); } } } Doc = null; Doc2 = null; App1 = null; App2 = null; Sel = null; Sel2 = null; ThisAddIn.g_log.Info("Copy AppointmentItem body to MailItem exit"); }
private void AfterReceiveUnsafe(object Item) { if (!CurrentSettings.AddInEnabled || CurrentSettings.IncomingFirstAction == IncomingFirstAction.DoNothing) { return; } Outlook.MailItem mailItem = Item as Outlook.MailItem; string senderAddress; if (!TryGetSenderAddress(mailItem, out senderAddress)) { return; } string domain; if (!TryGetDomain(senderAddress, out domain)) { return; } if (CurrentSettings.IncomingExceptions.Contains(domain)) { return; } var ruleName = IncomingRulePrefix + domain; var initChar = char.ToUpper(domain.Take(1).First()); var folderName = initChar.ToString() + domain.Substring(1); Outlook.MAPIFolder parentFolder = null; if (CurrentSettings.IncomingCreateParentFolders) { var parentFolderName = GetParentFolderName(initChar); if (!TryGetFolder(parentFolderName, Inbox, out parentFolder)) { parentFolder = CreateFolder(parentFolderName, Inbox); } } else { parentFolder = Inbox; } Outlook.MAPIFolder folder = null; if (!TryGetFolder(folderName, parentFolder, out folder)) { folder = CreateFolder(folderName, parentFolder); } if (CurrentSettings.IncomingSecondAction != IncomingSecondAction.DoNothing) { RefreshSearchFolders(); Outlook.MAPIFolder searchFolder = null; if (CurrentSettings.IncomingCreateParentFolders) { searchFolder = parentFolder; } else { searchFolder = folder; } if (!FolderExists(searchFolder.Name, SearchFolders)) { CreateSearchFolder(searchFolder); } } try { mailItem.Move(folder); } catch { // try to move, if it does not happen, ignore it } if (CurrentSettings.IncomingFirstAction == IncomingFirstAction.CreateInboxFolderRule) { RefreshRules(); var ruleSet = RuleSet; if (!RuleExists(ruleSet, ruleName)) { CreateIncomingRule(ruleSet, ruleName, domain, folder, mailItem); ruleSet.Save(false); } } }
private void CheckEmailSender() { Outlook.Selection selection = Globals.ThisAddIn.Application.ActiveExplorer().Selection; Outlook.MailItem email = null; if (selection.Count > 0) { email = selection[1] as Outlook.MailItem; } if (email is object) { if (email.Sender is object) { //Try to find contact from email adddress. InTouchContact emailContact = null; try { Outlook.ContactItem contact = InTouch.Contacts.FindContactFromEmailAddress(email.Sender.Address); if (contact is object) { emailContact = new InTouchContact(contact); } } catch (Exception ex) { Log.Error(ex); throw; } if (emailContact is object) { //Make the Contact Button visable and add the image and name to the button. Globals.Ribbons.RibExplorer.buttonContact.Visible = true; if (emailContact.FullName is object) { Globals.Ribbons.RibExplorer.buttonContact.Label = emailContact.FullName; } else { Globals.Ribbons.RibExplorer.buttonContact.Label = ""; } if (emailContact.HasPicture) { Globals.Ribbons.RibExplorer.buttonContact.Image = Image.FromFile(emailContact.GetContactPicturePath()); } else { Globals.Ribbons.RibExplorer.buttonContact.Image = Properties.Resources.contact; } //Check if the contact details are valid. if (!emailContact.CheckDetails()) { Globals.Ribbons.RibExplorer.buttonAttention.Visible = true; } emailContact.SaveAndDispose(); } else { //As the contact was not found, make the add contact button visible. Globals.Ribbons.RibExplorer.buttonAddContactPersonal.Visible = true; Globals.Ribbons.RibExplorer.buttonAddContactOther.Visible = true; Globals.Ribbons.RibExplorer.buttonAddContactJunk.Visible = true; } } else { Globals.Ribbons.RibExplorer.buttonAddContactPersonal.Visible = true; Globals.Ribbons.RibExplorer.buttonAddContactOther.Visible = true; Globals.Ribbons.RibExplorer.buttonAddContactJunk.Visible = true; } //if (email.EntryID != lastEntryID) //{ // //Track last EntryID as Explorer_SelectionChange event fires twice for each selection change. // lastEntryID = email.EntryID; // ClearButtons(); //} } if (email is object) { Marshal.ReleaseComObject(email); } if (selection is object) { Marshal.ReleaseComObject(selection); } }
private void AfterSendUnsafe(object Item) { if (!CurrentSettings.AddInEnabled || CurrentSettings.OutgoingFirstAction == OutgoingFirstAction.DoNothing) { return; } Outlook.MailItem mailItem = Item as Outlook.MailItem; var domains = new HashSet <string>(); foreach (Outlook.Recipient recipient in mailItem.Recipients) { string recipientAddress; if (!TryGetRecipientAddress(recipient, out recipientAddress)) { continue; } string domain; if (!TryGetDomain(recipientAddress, out domain)) { continue; } if (!domains.Contains(domain)) { domains.Add(domain); } } var domainsAllowed = domains.Except(CurrentSettings.OutgoingExceptions); Outlook.Rules ruleSet = null; var needsSave = false; if (domainsAllowed.Count() > 0 && CurrentSettings.OutgoingFirstAction == OutgoingFirstAction.CreateSentFolderRule) { RefreshRules(); ruleSet = RuleSet; } foreach (var domain in domainsAllowed) { var ruleName = OutgoingRulePrefix + domain; var initChar = char.ToUpper(domain.Take(1).First()); var folderName = SentboxFolderNamePrefix + initChar.ToString() + domain.Substring(1); Outlook.MAPIFolder parentFolder = null; if (CurrentSettings.OutgoingCreateParentFolders) { var parentFolderName = GetParentFolderName(initChar); if (!TryGetFolder(parentFolderName, Sentbox, out parentFolder)) { parentFolder = CreateFolder(parentFolderName, Sentbox); } } else { parentFolder = Sentbox; } Outlook.MAPIFolder folder = null; if (!TryGetFolder(folderName, parentFolder, out folder)) { folder = CreateFolder(folderName, parentFolder); } try { var copy = mailItem.Copy() as Outlook.MailItem; copy.Move(folder); } catch { // tried to move if it does not happen ignore } if (CurrentSettings.OutgoingFirstAction == OutgoingFirstAction.CreateSentFolderRule) { if (!RuleExists(ruleSet, ruleName)) { CreateOutgoingRule(ruleSet, ruleName, domain, folder, mailItem); needsSave = true; } } } if (needsSave && ruleSet != null) { ruleSet.Save(false); } }
void growl_NotificationCallback(Growl.Connector.Response response, Growl.Connector.CallbackData callbackData) { if (callbackData != null && callbackData.Result == Growl.CoreLibrary.CallbackResult.CLICK) { string type = callbackData.Type; if (type != null && type != String.Empty) { string id = callbackData.Data; object obj = this.Session.GetItemFromID(id, Type.Missing); switch (type) { case "mailmessage": if (obj != null && obj is Outlook.MailItem) { Outlook.MailItem message = (Outlook.MailItem)obj; EnableFullActivation(); message.Display(false); DisableFullActivation(); } obj = null; break; case "multimessage": object aw = this.ActiveWindow(); if (aw is Microsoft.Office.Interop.Outlook.Explorer) { Microsoft.Office.Interop.Outlook.Explorer explorer = (Microsoft.Office.Interop.Outlook.Explorer)aw; EnableFullActivation(); explorer.Activate(); DisableFullActivation(); } else if (aw is Microsoft.Office.Interop.Outlook.Inspector) { Microsoft.Office.Interop.Outlook.Inspector inspector = (Microsoft.Office.Interop.Outlook.Inspector)aw; EnableFullActivation(); inspector.Activate(); DisableFullActivation(); } break; case "remindermail": if (obj != null && obj is Outlook.MailItem) { Outlook.MailItem item = (Outlook.MailItem)obj; EnableFullActivation(); item.Display(false); DisableFullActivation(); } obj = null; break; case "reminderappointment": if (obj != null && obj is Outlook.AppointmentItem) { Outlook.AppointmentItem item = (Outlook.AppointmentItem)obj; EnableFullActivation(); item.Display(false); DisableFullActivation(); } obj = null; break; case "remindertask": if (obj != null && obj is Outlook.TaskItem) { Outlook.TaskItem item = (Outlook.TaskItem)obj; EnableFullActivation(); item.Display(false); DisableFullActivation(); } obj = null; break; } } } }
private Outlook.Rule CreateOutgoingRule(Outlook.Rules ruleSet, string ruleName, string domain, Outlook.MAPIFolder folder, Outlook.MailItem mailItem) { Outlook.Rule rule = ruleSet.Create(ruleName, Outlook.OlRuleType.olRuleSend); // Rule Conditions // To condition rule.Conditions.RecipientAddress.Address = new string[] { "@" + domain }; rule.Conditions.RecipientAddress.Enabled = true; // Rule Exceptions // nothing yet // Rule Actions rule.Actions.CopyToFolder.Folder = folder; rule.Actions.CopyToFolder.Enabled = true; rule.Enabled = true; return(rule); }
private void OnToolbarItemClicked(object sender, ToolStripItemClickedEventArgs e) { //Toolbar handler - forward to main menu handler long id = 0; Issue.Action action = null; Issue.Attachment attachment = null; try { //Get the current action id = Convert.ToInt64(this.lsvActions.SelectedItems[0].Name); action = this.mIssue.Item(id); switch (e.ClickedItem.Name) { case "btnNew": this.ctxActionsNew.PerformClick(); break; case "btnPrint": this.ctxActionsPrint.PerformClick(); break; case "btnRefresh": this.ctxRefresh.PerformClick(); break; case "btnOpen": //Open the selected attachment attachment = action.Item(this.lsvAttachments.SelectedItems[0].Text); attachment.Open(); break; case "btnAttach": //Save an attachment to the selected action OpenFileDialog dlgOpen = new OpenFileDialog(); dlgOpen.AddExtension = true; dlgOpen.Filter = "All Files (*.*) | *.*"; dlgOpen.FilterIndex = 0; dlgOpen.Title = "Select Attachment to Save..."; dlgOpen.FileName = ""; if (dlgOpen.ShowDialog(this) == DialogResult.OK) { attachment = action.Item(0); attachment.Filename = dlgOpen.FileName; attachment.Save(); OnActionSelected(null, EventArgs.Empty); } break; case "btnSend": if (this.lsvActions.SelectedItems.Count > 0) { //Create new mail item if (OutlookApp == null) { return; } Outlook.MailItem item = (Outlook.MailItem)OutlookApp.CreateItem(Outlook.OlItemType.olMailItem); item.Subject = this._Issue.Subject; item.Body = action.Comment; item.To = EnterpriseFactory.GetContact(this._Issue.ContactID).Email; item.Display(false); } break; } } catch (Exception ex) { reportError(new ControlException("Unexpected error in IssueInspector.", ex)); } }
private void Application_ItemSend(object Item, ref bool Cancel) { var item = Item as Outlook.MailItem; // Retrieve Settings var host = Properties.Settings.Default.Host; var account = Properties.Settings.Default.Account; var password = Properties.Settings.Default.Password; var contractAddress = Properties.Settings.Default.Contract; // Get the item properties (that were set by the ribbon check boxes) var isBlockchain = item.UserProperties == null || item.UserProperties["BlockchainStamp"] == null ? false : item.UserProperties["BlockchainStamp"].Value; var isNotify = item.UserProperties == null || item.UserProperties["BlockchainNotify"] == null ? false : item.UserProperties["BlockchainNotify"].Value; // If yes, calculate the hash and send it to the Smart Contract if (isBlockchain) { // Temporarily save the full item to disk and read back the contents var tempFile = Path.GetTempFileName(); item.SaveAs(tempFile, Outlook.OlSaveAsType.olMSG); var itemMsgBytes = File.ReadAllBytes(tempFile); // Serialize item to JSON //var itemJson = JsonConvert.SerializeObject(itemMsg); // Calculate SHA256 hash //byte[] bytes = Encoding.UTF8.GetBytes(itemMsg); SHA256Managed sha256 = new SHA256Managed(); byte[] hashbytes = sha256.ComputeHash(itemMsgBytes); StringBuilder hashstring = new StringBuilder("0x"); foreach (Byte b in hashbytes) { hashstring.Append(b.ToString("x2")); } var hash = hashstring.ToString(); // Get message properties var subject = item.Subject; var sender = Application.Session.Accounts[1].SmtpAddress; // Use default account var itemRecipients = item.Recipients; StringBuilder recipientsstring = new StringBuilder(); foreach (Outlook.Recipient r in itemRecipients) { recipientsstring.Append(r.Address); if (r.Index < itemRecipients.Count - 1) { recipientsstring.Append(";"); } } var recipients = recipientsstring.ToString(); // Blockchain hash var web3 = new Nethereum.Web3.Web3(host); // Unlock account // Need to expose the personal API: // start geth --datadir Ethereum-Private --networkid 42 --nodiscover --rpc --rpcapi eth,web3,personal --rpccorsdomain "*" console try { web3.Personal.UnlockAccount.SendRequestAsync(account, password, new HexBigInteger(120)).Wait(); } catch (Exception ex) { // Ignore errors //MessageBox.Show(ex.Message); } // Send transaction var abi = @"[{ ""constant"":false,""inputs"":[{""name"":""hash"",""type"":""uint256""},{""name"":""path"",""type"":""string""},{""name"":""computer"",""type"":""string""}],""name"":""fossilizeDocument"",""outputs"":[],""type"":""function""},{""constant"":true,""inputs"":[{""name"":"""",""type"":""uint256""}],""name"":""emails"",""outputs"":[{""name"":""sender"",""type"":""address""},{""name"":""subject"",""type"":""string""},{""name"":""emailFrom"",""type"":""string""},{""name"":""emailTo"",""type"":""string""}],""type"":""function""},{""constant"":false,""inputs"":[{""name"":""hash"",""type"":""uint256""},{""name"":""subject"",""type"":""string""},{""name"":""emailFrom"",""type"":""string""},{""name"":""emailTo"",""type"":""string""}],""name"":""fossilizeEmail"",""outputs"":[],""type"":""function""},{""constant"":true,""inputs"":[{""name"":"""",""type"":""uint256""}],""name"":""documents"",""outputs"":[{""name"":""sender"",""type"":""address""},{""name"":""path"",""type"":""string""},{""name"":""computer"",""type"":""string""}],""type"":""function""},{""anonymous"":false,""inputs"":[{""indexed"":false,""name"":""timestamp"",""type"":""uint256""},{""indexed"":true,""name"":""sender"",""type"":""address""},{""indexed"":false,""name"":""path"",""type"":""string""},{""indexed"":false,""name"":""computer"",""type"":""string""}],""name"":""DocumentFossilized"",""type"":""event""},{""anonymous"":false,""inputs"":[{""indexed"":false,""name"":""timestamp"",""type"":""uint256""},{""indexed"":true,""name"":""sender"",""type"":""address""},{""indexed"":false,""name"":""subject"",""type"":""string""},{""indexed"":false,""name"":""emailFrom"",""type"":""string""},{""indexed"":false,""name"":""emailTo"",""type"":""string""}],""name"":""EmailFossilized"",""type"":""event""}]"; var contract = web3.Eth.GetContract(abi, contractAddress); var fossilizeFunc = contract.GetFunction("fossilizeEmail"); fossilizeFunc.SendTransactionAsync(account, new HexBigInteger(1000000), new HexBigInteger(0), hash, subject, sender, recipients).Wait(); // Send a confirmation e-mail Outlook.MailItem newItem = (Outlook.MailItem) this.Application.CreateItem(Outlook.OlItemType.olMailItem); newItem.Subject = "Message stamp confirmation " + hash; newItem.Body = "This is a confirmation that the attached message has been stamped in the blockchain with hash " + hash + "."; newItem.Attachments.Add(tempFile, Outlook.OlAttachmentType.olEmbeddeditem); // Do we need to notify the recipients? if (isNotify) { StringBuilder notifyTo = new StringBuilder(sender); notifyTo.Append(";"); // Also include recipients in the confirmation message foreach (Outlook.Recipient r in itemRecipients) { notifyTo.Append(r.Address); if (r.Index < itemRecipients.Count - 1) { notifyTo.Append(";"); } } // Set recipients newItem.To = notifyTo.ToString(); } else { newItem.To = sender; } // Send the message newItem.Send(); } }
private void button1_Click(object sender, EventArgs e) { NS = App.GetNamespace("MAPI"); CheckFold = GetFolder(NS.Folders, "Sample"); //MovingFold = GetFolder(NS.Folders, "HK_MailRead"); //ErrMovingFold = GetFolder(NS.Folders, "HK_ErrMail"); ObjOutlook.Items olmailItems = CheckFold.Items; int iter = 0; try { //ObjOutlook.MAPIFolder ChkFld = NS.GetDefaultFolder(ObjOutlook.OlDefaultFolders.olFolderInbox); if (CheckFold.Items.Count > 0) { // foreach (ObjOutlook.MailItem ListItem in ChkFld.Items) //{ for (int iteration = 1; iteration <= CheckFold.Items.Count; iteration++) { ObjOutlook.MailItem ListItem = (ObjOutlook.MailItem)CheckFold.Items[iteration]; // } MailsSub = ListItem.Subject; if (MailsSub.ToLower().StartsWith("RE") || MailsSub.ToLower().StartsWith("Ka")) { //Cc = ListItem.CC.ToString(); //To = ListItem.To.ToString(); //Bcc = ListItem.To.ToString(); //SenderMailAddr = ListItem.SenderEmailAddress.ToString(); } ObjOutlook.Items ioItems = (ObjOutlook.Items)CheckFold.Items; string emailname; string emailWithDomainName; foreach (ObjOutlook.MailItem olMail in olmailItems) { foreach (ObjOutlook.Recipient olRecipient in olMail.Recipients) { // string address = olRecipient.AddressEntry.GetExchangeUser().Address.ToString(); try { emailname = olRecipient.Name; emailWithDomainName = GetEmailAddressFromExchange(emailname); emailCollection[iter] = emailWithDomainName; iter++; // ObjOutlook.ContactItem oCt = (ObjOutlook.ContactItem)olmailItems; //string emaill = oCt.Email1Address.ToString(); } catch { } try { AddAddress(olRecipient.Address); } catch { } } } try { Cc = ListItem.CC.ToString(); } catch { } try { To = ListItem.To.ToString(); } catch { } try { Bcc = ListItem.To.ToString(); } catch { } try { SenderMailAddr = ListItem.SenderEmailAddress.ToString(); } catch { } } } } catch { } for (int i = 0; i < emailCollection.Count; i++) { listBox1.Items.Add(emailCollection[i].ToString()); } }
/// <summary> /// 将邮件保存到公共盘 /// </summary> /// <param name="myItem">要保存的邮件</param> /// <param name="mailSaveNameFilePath">保存邮件的完整路径</param> private void SaveMailItemToDisk(Outlook.MailItem myItem, string mailSaveNameFilePath) { myItem.SaveAs(mailSaveNameFilePath); }
/// <summary> /// Event if receive new mail /// </summary> /// <param name="EntryIDItem">Entry ID mail</param> private void Application_NewMailEx(string EntryIDItem) { try { //for other location inbox folder (eg. IMAP) -> Type.Missing (diffent store, pst file) Outlook.MailItem mail = Application.Session.GetItemFromID(EntryIDItem, Type.Missing) as Outlook.MailItem; if (previousProcessMail == mail.EntryID) { return; } if (previousMoveProecessMail == mail.EntryID) { return; } previousProcessMail = mail.EntryID; //older location inbox folder (default) work only POP3 and Exchange //Outlook.MailItem mail = Application.Session.GetItemFromID(EntryIDItem, Application.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox).StoreID) as Outlook.MailItem; //if receive not mail exit function (eg. read raport etc) if (mail == null) { return; } Outlook.PropertyAccessor pAccess = mail.PropertyAccessor; string mailHeader = pAccess.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E").ToString(); bool IsSpam = false; try { //new algoritm (>2.0.6) string fsIpStep1 = mailHeader.Substring(0, mailHeader.IndexOf(")")); string ipToVerify = fsIpStep1.Substring(fsIpStep1.IndexOf("(") + 1, fsIpStep1.Length - fsIpStep1.IndexOf("(") - 1); if (!IsAddressValid(ipToVerify)) { fsIpStep1 = mailHeader.Substring(mailHeader.IndexOf("Received: from"), mailHeader.Length - mailHeader.IndexOf("Received: from")); string fsIpStep2 = fsIpStep1.Substring(0, fsIpStep1.IndexOf("]")); ipToVerify = fsIpStep2.Substring(fsIpStep2.IndexOf("[") + 1, fsIpStep2.Length - fsIpStep2.IndexOf("[") - 1); } //old algoritm (<=2.0.5.2) //string fsIpStep1 = mailHeader.Substring(mailHeader.IndexOf("Received: from"), mailHeader.Length - mailHeader.IndexOf("Received: from")); //string fsIpStep2 = fsIpStep1.Substring(0, fsIpStep1.IndexOf("]")); //string ipToVerify = fsIpStep2.Substring(fsIpStep2.IndexOf("[") + 1, fsIpStep2.Length - fsIpStep2.IndexOf("[") - 1); //string[] BLS = new string[] { "sbl-xbl.spamhaus.org", "bl.spamcop.net" }; string[] BLS = new string[listBLS.Count]; int i = 0; foreach (string oServer in listBLS) { BLS[i] = oServer; i++; } VerifyIP IP = new VerifyIP(ipToVerify, BLS); if (IP.BlackList.IsListed) //Is the IP address listed? { IsSpam = true; } //bellow line only test (all message this spam) remove after publish //IsSpam = true; } catch (Exception ex) { SaveToLog("Error reading message header:\n\r" + mailHeader + "\n\r" + ex.Message, pathToErrorLog); } if (IsSpam) { //check if mail sender is a white list if (!IsSenderSafe(mail.SenderEmailAddress)) { //bellow variable to idetyfity error bool bDefaultJunkFolder = false; try { //if spam folder user choosed if (!string.IsNullOrEmpty(entryIDSpamFolder) && !string.IsNullOrEmpty(entryIDStoreSpamFolder)) { bDefaultJunkFolder = false; mail.Move(Application.Session.GetFolderFromID(entryIDSpamFolder, entryIDStoreSpamFolder) as Outlook.Folder); Outlook.Folder spamFol = Application.Session.GetFolderFromID(entryIDSpamFolder, entryIDStoreSpamFolder) as Outlook.Folder; foreach (Outlook.MailItem item in spamFol.Items) { if (item.ReceivedTime == mail.ReceivedTime) { ChangeEmailSubject(item); previousMoveProecessMail = item.EntryID; break; } } //free COM object Marshal.ReleaseComObject(spamFol); GC.SuppressFinalize(spamFol); spamFol = null; } //if isn't, default "JunkFolder" else { bDefaultJunkFolder = true; mail.Move(Application.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderJunk)); Outlook.Folder spamFol = Application.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderJunk) as Outlook.Folder; foreach (Outlook.MailItem item in spamFol.Items) { if (item.ReceivedTime == mail.ReceivedTime) { ChangeEmailSubject(item); previousMoveProecessMail = item.EntryID; break; } } //free COM object Marshal.ReleaseComObject(spamFol); GC.SuppressFinalize(spamFol); spamFol = null; } } catch (Exception ex) { SaveToLog("Error moving mail to spam folder:\n\r" + ex.Message + "\n\r" + "Default JunkFolder = " + bDefaultJunkFolder, pathToErrorLog); } } } //free COM object Marshal.ReleaseComObject(pAccess); GC.SuppressFinalize(pAccess); pAccess = null; Marshal.ReleaseComObject(mail); GC.SuppressFinalize(mail); mail = null; } catch (Exception ex) { SaveToLog("Error plugin:\n\r" + ex.Message, pathToErrorLog); } }
/// <summary> /// 将邮件信息存储到数据库中 /// </summary> /// <param name="myItem">邮件Item</param> /// <param name="saveMailNamePath">传出参数,传出要存储的路径</param> private void AddMailToDB(Outlook.MailItem myItem, out string saveMailNamePath) { Record record = new Record(); record.M_subject = ""; if (myItem.Subject != null) { record.M_subject = " " + myItem.Subject.Trim(); //邮件主题 } record.M_importance = 0.ToString(); if (myItem.Importance != null) { record.M_importance = ((int)myItem.Importance).ToString(); } record.M_sender = myItem.SenderName.Trim(); record.M_mailincometime = Convert.ToDateTime(myItem.ReceivedTime.ToString("G")); record.JOBID = record.M_subject + "-" + DateTime.Now.ToString(); record.T1 = Convert.ToDateTime(DateTime.Now.ToString("G")); //寻找关键字 record.M_requestID = FindRequestKeyWord(record.M_subject); string mailBody = myItem.Body.Trim(); record.M_statu = "0"; int?preAsignEmpId = 0; string subjectStrGet = RegexHelper.ReplaceStrByRegex(@"RE:|FW:|回复:", record.M_subject, ""); preAsignEmpId = FindRecordByRequest("%" + subjectStrGet.Substring(0, subjectStrGet.Length) + "%"); if (preAsignEmpId != null) { record.M_statu = "4"; record.M_asign = preAsignEmpId; } else { record.M_statue = "0"; record.M_asign = 0; } string saveMailName = record.M_requestID + "-" + new Random().GetHashCode().ToString() + myItem.ReceivedTime.ToString("yyyyMMddHHmmss") + mailNum.ToString(); //邮件保存在公共盘上的名字 saveMailNamePath = MailHelper.MailFolder + saveMailName + ".msg"; record.M_filePath = saveMailNamePath; Count count = new Count(); count.M_subject = record.M_subject; count.M_mailincometime = record.M_mailincometime; //将邮件记录添加到DB中 AddRecordToDB(record); AddCountToDB(count); }
/** * Classifies email based on weighted sum of subject and body * classification confidences. * * @param moveMail * candidate email to classify * * @returns classification and confidence of given email * * @author Kurtis Kuszmaul **/ private Tuple <string, double> ClassifyMail(Outlook.MailItem moveMail) { string classification; double subConfWeight = .47; double bodyConfWeight = .53; double matchingConfLimit = .85; double differentConfLimit = .45; // Classify subject ClassifyInput classifySubjectInput = new ClassifyInput { Text = moveMail.Subject }; // Get top class and weighted confidence of subject Classification classifySubjectResult = _subClassifier.Classify(subClassifierID, classifySubjectInput); string subClass = classifySubjectResult.TopClass; double subConf = (double)classifySubjectResult.Classes[0].Confidence * subConfWeight; Dictionary <string, List <double> > bodyDict = new Dictionary <string, List <double> >(); List <double> spamList = new List <double>(); List <double> notSpamList = new List <double>(); bodyDict.Add("spam", spamList); bodyDict.Add("not spam", notSpamList); // Break subject into manageable chunks to classify string cleanedBody = moveMail.Body.Replace("\n", " ").Replace("\t", " ").Replace("\r", " "); IList <string> bodyChunks = ChunkBody(cleanedBody, 1000); foreach (string chunk in bodyChunks) { string cleanedChunk = chunk; // Classify chunk of body text ClassifyInput classifyChunkInput = new ClassifyInput { Text = chunk }; // Get top class of body chunk and add it and its confidence to bodyDict Classification classifyChunkResult = _bodyClassifier.Classify(bodyClassifierID, classifyChunkInput); string topChunkClass = classifyChunkResult.TopClass; double chunkConf = (double)classifyChunkResult.Classes[0].Confidence; bodyDict[topChunkClass].Add(chunkConf); } // Determine top classification of body and take average weighted confidence of chunks string bodyClass = bodyDict["spam"].Count > bodyDict["not spam"].Count ? "spam" : "not spam"; List <double> bodyConfList = bodyDict[bodyClass]; double bodyConf = bodyConfList.Average() * bodyConfWeight; // Combine classes and weighted confidences to determine final classification double totalConf; if (subClass == bodyClass) { totalConf = subConf + bodyConf; if (totalConf >= matchingConfLimit) { classification = subClass; } else { classification = "not spam"; totalConf = -1.0; } } else { if (subConf > bodyConf && subConf > differentConfLimit) { classification = subClass; totalConf = subConf / subConfWeight; } else if (bodyConf >= subConf && bodyConf > differentConfLimit) { classification = bodyClass; totalConf = bodyConf / bodyConfWeight; } else { classification = "not spam"; totalConf = -1.0; } } totalConf *= 100; totalConf = Math.Round(totalConf, 2); return(Tuple.Create <string, double>(classification, totalConf)); }
public void MessageChanged(Outlook.MailItem mailItem) { ConversationID = mailItem.ConversationID ?? PreviousConversationID; PreviousConversationID = ConversationID; LoadNotes(ConversationID); }
private static void OutlookApp(out Outlook.Application oApp, out Outlook.MailItem oMsg) { oApp = new Outlook.Application(); oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); }
void InboxFolderItemAdded(object Item) { if (Item is Outlook.MailItem) { Outlook.MailItem mail = (Outlook.MailItem)Item; if (Item != null) { int index; mainform.textBox1.Text = mail.Subject; Regex time = new Regex(@"\b\d{1,2}\:\d{1,2}\ [AaPpMm]{2}"); Regex IP = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"); if (mail.SenderEmailAddress == "*****@*****.**") { Regex word = new Regex(@"\w+"); Match mIP = IP.Match(mail.Body); Match service = Regex.Match(mail.Subject, @"(?<before>[A-Za-z0-9,]+|[A-Za-z0-9,]+\s[0-9]+) Down (?<after>\w+)", RegexOptions.IgnoreCase); index = SearchGroup(0, word.Matches(mail.Subject)[1].Value); if (mail.Subject.ToUpper().Contains("Down".ToUpper())) { //Match result2 = time.Match(mail.Subject); if (index != -1) { mainform.customcontrol11.listView1.Items[index].SubItems[2].Text = service.Groups["before"].ToString(); } else { ListViewItem li = new ListViewItem(word.Matches(mail.Subject)[1].Value, 1); li.SubItems.Add(mIP.Value); li.SubItems.Add(service.Groups["before"].ToString()); li.SubItems.Add("Down"); li.SubItems.Add(mail.ReceivedTime.ToShortTimeString()); li.Group = mainform.customcontrol11.listView1.Groups[0]; mainform.customcontrol11.listView1.Items.Add(li); } } else if (mail.Subject.ToUpper().Contains("UP".ToUpper())) { if (index != -1) { if (mainform.customcontrol11.listView1.Items[index].SubItems[3].Text == "Down") { mainform.customcontrol11.listView1.Items[index].Group = mainform.customcontrol11.listView1.Groups[6]; } } } } else if (mail.SenderEmailAddress == "*****@*****.**") { var url = Regex.Match(mail.Body, @"(?<=URL: )(.+?)(?=\n|,)"); if (mail.Subject.Contains("Sitescope Alert, error")) { if (mainform.customcontrol11.listView1.FindItemWithText(url.Value) == null) { ListViewItem li = new ListViewItem("Url Down", 3); li.SubItems.Add(url.Value); li.SubItems.Add(""); li.SubItems.Add(mail.ReceivedTime.ToShortTimeString()); li.Group = mainform.customcontrol11.listView1.Groups[3]; mainform.customcontrol11.listView1.Items.Add(li); } } else if (mail.Subject.Contains("Sitescope Alert, good")) { if (mainform.customcontrol11.listView1.FindItemWithText(url.Value) != null) { mainform.customcontrol11.listView1.FindItemWithText(url.Value).Remove(); } } } else if (mail.SenderEmailAddress == "*****@*****.**") { var space = Regex.Match(mail.Subject, @"(?<=Alert: Percent Space Used of )(.+?)(?=-)"); var spaceReset = Regex.Match(mail.Subject, @"(?<=Reset: Percent Space Used of )(.+?)(?=-)"); var percent = Regex.Match(mail.Subject, @"(?<=is now )(.+?)(?=%)"); index = SearchGroup(1, space.Value); if (mail.Subject.Contains("Alert: Percent Space")) { if (index == -1) { ListViewItem li = new ListViewItem(space.Value, 0); li.SubItems.Add(IP.Match(mail.Body).Value); li.SubItems.Add(percent.Value + "%"); li.SubItems.Add("space"); li.SubItems.Add(mail.ReceivedTime.ToShortTimeString()); li.Group = mainform.customcontrol11.listView1.Groups[1]; mainform.customcontrol11.listView1.Items.Add(li); } else { mainform.customcontrol11.listView1.Items[index].SubItems[2].Text = percent.Value + "%"; } } else if (mail.Subject.Contains("Reset: Percent Space")) { index = SearchGroup(1, spaceReset.Value); if (index != -1) { mainform.customcontrol11.listView1.Items[index].Group = mainform.customcontrol11.listView1.Groups[6]; mainform.customcontrol11.listView1.Items[index].SubItems[2].Text = percent.Value + "%"; } } else if (mail.Subject.Contains("Alert: CPU Load")) { var cpuname = Regex.Match(mail.Subject, @"(?<=Alert: CPU Load on )(.+?)(?=-)"); index = SearchGroup(8, cpuname.Value); if (index == -1) { ListViewItem li = new ListViewItem(cpuname.Value, 0); li.SubItems.Add(IP.Match(mail.Subject).Value); li.SubItems.Add(percent.Value + "%"); li.SubItems.Add("CPU"); li.SubItems.Add(mail.ReceivedTime.ToShortTimeString()); li.Group = mainform.customcontrol11.listView1.Groups[8]; mainform.customcontrol11.listView1.Items.Add(li); } else { mainform.customcontrol11.listView1.Items[index].SubItems[2].Text = percent.Value + "%"; } } else if (mail.Subject.Contains("Reset : CPU Load on")) { var cpuresetname = Regex.Match(mail.Subject, @"(?<=Reset : CPU Load on )(.+?)(?=-)"); index = SearchGroup(8, cpuresetname.Value); if (index != -1) { mainform.customcontrol11.listView1.Items[index].Remove(); } } else if (mail.Subject.Contains("Alert: Memory Utilized on")) { var memname = Regex.Match(mail.Subject, @"(?<=Alert: Memory Utilized on )(.+?)(?=-)"); index = SearchGroup(10, memname.Value); if (index == -1) { ListViewItem li = new ListViewItem(memname.Value, 0); li.SubItems.Add(IP.Match(mail.Subject).Value); li.SubItems.Add(percent.Value + "%"); li.SubItems.Add("Mem"); li.SubItems.Add(mail.ReceivedTime.ToShortTimeString()); li.Group = mainform.customcontrol11.listView1.Groups[10]; mainform.customcontrol11.listView1.Items.Add(li); } else { mainform.customcontrol11.listView1.Items[index].SubItems[2].Text = percent.Value + "%"; } } else if (mail.Subject.Contains("Reset : Memory Utilized on")) { var memresetname = Regex.Match(mail.Subject, @"(?<=Reset : Memory Utilized on )(.+?)(?=-)"); index = SearchGroup(10, memresetname.Value); if (index != -1) { mainform.customcontrol11.listView1.Items[index].Remove(); } } else if (mail.Subject.Contains("Reboot")) { var servreName = Regex.Match(mail.Body, @"(?<=ALERT: )(.+?)(?= -)"); ListViewItem li = new ListViewItem(servreName.Value, 4); li.SubItems.Add(IP.Match(mail.Body).Value); li.SubItems.Add(time.Match(mail.Body).Value); li.SubItems.Add("Reboot"); li.Group = mainform.customcontrol11.listView1.Groups[2]; mainform.customcontrol11.listView1.Items.Add(li); } } else if (mail.SenderEmailAddress == "*****@*****.**") { var siteDown = Regex.Match(mail.Subject, @"(.+?)(?= is Down)"); var siteUp = Regex.Match(mail.Subject, @"(.+?)(?= is Up)"); if (mail.Subject.Contains("Down")) { ListViewItem li = new ListViewItem(siteDown.Value, 1); li.SubItems.Add(""); li.SubItems.Add("24*7"); li.SubItems.Add("Down"); li.SubItems.Add(mail.ReceivedTime.ToShortTimeString()); li.Group = mainform.customcontrol11.listView1.Groups[11]; mainform.customcontrol11.listView1.Items.Add(li); } else if (mail.Subject.Contains("Up")) { index = SearchGroup(11, siteUp.Value); if (index != -1) { mainform.customcontrol11.listView1.Items[index].Group = mainform.customcontrol11.listView1.Groups[6]; } } } else if (mail.SenderEmailAddress == "*****@*****.**") { var servreName = Regex.Match(mail.Subject, @"(?<=Server: )(.+?)(?=\))"); var jobName = Regex.Match(mail.Subject, @"(?<=Job: )(.+?)(?=\))"); ListViewItem li = new ListViewItem(servreName.Value, 2); if (mail.Subject.Contains("Job Failed")) { li.SubItems.Add(""); li.SubItems.Add("failed Job"); li.SubItems.Add("Backup"); li.SubItems.Add(jobName.Value); li.SubItems.Add(mail.ReceivedTime.ToShortTimeString()); li.Group = mainform.customcontrol11.listView1.Groups[7]; mainform.customcontrol11.listView1.Items.Add(li); } else if (mail.Subject.Contains("Job Cancellation")) { li.SubItems.Add(""); li.SubItems.Add("cancelled Job"); li.SubItems.Add("Backup"); li.SubItems.Add(jobName.Value); li.SubItems.Add(mail.ReceivedTime.ToShortTimeString()); li.Group = mainform.customcontrol11.listView1.Groups[7]; mainform.customcontrol11.listView1.Items.Add(li); } } else if (mail.SenderEmailAddress == "*****@*****.**") { var downName = Regex.Match(mail.Subject, @"(?<=Alarm: )(.+?)(?=is Down|is Critical)"); var upName = Regex.Match(mail.Subject, @"(?<=Alarm: )(.+?)(?=is Up|is Clear)"); index = SearchGroup(4, downName.Value); if (mail.Subject.Contains("Down") || mail.Subject.Contains("Critical")) { if (index == -1) { index = SearchGroup(4, downName.Value); } ListViewItem li = new ListViewItem(downName.Value, 3); li.SubItems.Add(""); li.SubItems.Add(time.Match(mail.Body).Value); li.SubItems.Add("Down"); li.Group = mainform.customcontrol11.listView1.Groups[4]; mainform.customcontrol11.listView1.Items.Add(li); } else if (mail.Subject.Contains("Up") || mail.Subject.Contains("Clear")) { index = SearchGroup(4, upName.Value); if (index != -1) { mainform.customcontrol11.listView1.Items[index].Remove(); } } } else if (mail.SenderEmailAddress == "*****@*****.**") { ListViewItem li = new ListViewItem(mail.Subject, 2); li.SubItems.Add(IP.Match(mail.Body).Value); li.SubItems.Add("failed"); li.SubItems.Add("SQL Job"); li.SubItems.Add(mail.ReceivedTime.ToShortTimeString()); li.Group = mainform.customcontrol11.listView1.Groups[9]; mainform.customcontrol11.listView1.Items.Add(li); } } } }
bool IsCheckinResult(Outlook.MailItem mail) { return(mail.Sender.Address.ToLower().Equals("*****@*****.**") && mail.Subject.Contains("[EmailTag]")); }
private void button1_Click(object sender, EventArgs e) { // Create the Outlook application. // in-line initialization Outlook.Application oApp = new Outlook.Application(); // Get the MAPI namespace. Outlook.NameSpace oNS = oApp.GetNamespace("mapi"); // Log on by using the default profile or existing session (no dialog box). oNS.Logon(Missing.Value, Missing.Value, false, true); // Alternate logon method that uses a specific profile name. // TODO: If you use this logon method, specify the correct profile name // and comment the previous Logon line. //oNS.Logon("profilename",Missing.Value,false,true); //Get the Inbox folder. Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //Get the Items collection in the Inbox folder. Outlook.Items oItems = oInbox.Items; // Get the first message. // Because the Items folder may contain different item types, // use explicit typecasting with the assignment. Outlook.MailItem oMsg = (Outlook.MailItem)oItems.GetFirst(); //Output some common properties. textBox1.Text = (oMsg.Subject); textBox1.Text += textBox1.Text + oMsg.SenderName; textBox1.Text += textBox1.Text + oMsg.ReceivedTime; textBox1.Text += textBox1.Text + oMsg.Body; //Check for attachments. int AttachCnt = oMsg.Attachments.Count; textBox1.Text += textBox1.Text + ("Attachments: " + AttachCnt.ToString()); //TO DO: If you use the Microsoft Outlook 11.0 Object Library, uncomment the following lines. if (AttachCnt > 0) { for (int i = 1; i <= AttachCnt; i++) { textBox1.Text += textBox1.Text + (i.ToString() + "-" + oMsg.Attachments[i].DisplayName); } } //Display the message. oMsg.Display(false); //modal //Log off. oNS.Logoff(); //Explicitly release objects. oMsg = null; oItems = null; oInbox = null; oNS = null; oApp = null; }
private void Btn_Add_User_Click(object sender, RoutedEventArgs e) { try { if ((TextBoxUserName.Text == "") || (TextBoxUserEmail.Text == "") || (Combo_User_Role.Text == "")) { if (TextBoxUserName.Text == "") { MessageBox.Show("Name is required", "Warning", MessageBoxButton.OK); TextBoxUserName.Focus(); } else if (TextBoxUserEmail.Text == "") { MessageBox.Show("Email is required", "Warning", MessageBoxButton.OK); TextBoxUserEmail.Focus(); } else if (Combo_User_Role.Text == "") { MessageBox.Show("Role is required", "Warning", MessageBoxButton.OK); Combo_User_Role.Focus(); } } else { MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Are You Sure?", "Insert Confirmation", System.Windows.MessageBoxButton.YesNo); if (messageBoxResult == MessageBoxResult.Yes) { string Password = Guid.NewGuid().ToString(); var checkuseremail = connection.Users.FirstOrDefault(S => S.Email == TextBoxUserEmail.Text); var userrole = connection.Roles.FirstOrDefault(Y => Y.Id == cb_role); if (checkuseremail == null) { var input_user = new User(TextBoxUserName.Text, TextBoxUserEmail.Text, Password, userrole); connection.Users.Add(input_user); var insert = connection.SaveChanges(); if (insert >= 1) { MessageBox.Show("User has been inserted"); } TB_M_User.ItemsSource = connection.Users.ToList(); Outlook._Application openapp = new Outlook.Application(); Outlook.MailItem sentmail = (Outlook.MailItem)openapp.CreateItem(Outlook.OlItemType.olMailItem); sentmail.To = TextBoxUserEmail.Text; sentmail.Subject = "Your Password " + DateTime.Now.ToString("dd/MM/yyyy"); sentmail.Body = "Dear " + TextBoxUserName.Text + "\nThis Is Your Password : "******"Your email has been sent!", "Message", MessageBoxButton.OK); reset_adduser(); } else { MessageBox.Show("Email has been used"); } } } } catch (Exception ex) { } }
public static List <printumBestellPositionen> createNewEmailmitAnhang(string pfad, string bestellnr, int _projektnr, string email) { projektnr = _projektnr; pdfPfad = pfad.Substring(0, pfad.Length - 4) + @".pdf"; mailPfad = pfad.Substring(0, pfad.Length - 4) + @".msg"; string mailtemplate = @"\\192.168.26.250\PT-99-Vorl\Dokumente\BestellungsMail-Template.oft"; Excel.Application excelApp = new Excel.Application(); Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(pfad); // Zeilen auslesen und in die Datenbank schreiben. bestellliste = ExcelHelper.getBestellPositionen(excelWorkbook, bestellnr); excelWorkbook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, pdfPfad); excelWorkbook.Close(false, pfad, null); excelApp.Quit(); Marshal.ReleaseComObject(excelWorkbook); Marshal.ReleaseComObject(excelApp); Outlook.Application app = new Outlook.Application(); Outlook.Folder folder = app.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts) as Outlook.Folder; dieMail = app.CreateItemFromTemplate(mailtemplate, folder) as Outlook.MailItem; Outlook.Inspector mailInspector = dieMail.GetInspector; mailInspector.Activate(); dieMail.Subject = "PT-PRINTUM Bestellung " + bestellnr + " Projekt: " + projektnr.ToString(); dieMail.To = email; dieMail.BodyFormat = Outlook.OlBodyFormat.olFormatHTML; //var textt = dieMail.HTMLBody; //textt.Replace(@"</body>", @"<b>Hinweis</b>:" + // @"Bitte geben Sie immer unsere kompletten Bestelldaten(Printum Auftrags Nr.und Bestell Nr.) auf allen" + // @"Schriftstücken zum Auftrag(Auftragsbestätigung, Lieferschein und Rechnung) vollständig an!" + // @"Fehlende oder unvollständige Bestelldaten können ansonsten ggf. zu einem verzögertem Zahlungsausgleich führen. </body>"); //dieMail.HTMLBody = textt; dieMail.Attachments.Add( pdfPfad, Outlook.OlAttachmentType.olByValue, 1, "PT-PRINTUM Bestellung " + bestellnr); dieMail.Display(true); Form4_Spinner f4 = (Application.OpenForms["Form4_Spinner"] as Form4_Spinner); if (f4 != null) { f4.Close(); } ((Outlook.ItemEvents_10_Event)dieMail).Send += ThisMai_send; return(bestellliste); }
/// <summary> /// MailItemの送信者情報(Dto)を取得する /// </summary> /// <param name="Item">MailItemオブジェクト</param> /// <returns>送信者の宛先情報DTO(送信者が取得できない場合null)</returns> private static RecipientInformationDto GetSenderInformation(Outlook.MailItem item) { Outlook.AddressEntry addressEntry; Outlook.ExchangeUser exchUser; Outlook.Recipient recipient; Outlook.ContactItem contactItem; //Office365(Exchangeユーザー)からのメール if (item.Sender != null) { addressEntry = item.Sender; recipient = Globals.ThisAddIn.Application.Session.CreateRecipient(addressEntry.Address); exchUser = getExchangeUser(recipient.AddressEntry); } //送信元メールアドレスが取れた場合 else if (item.SenderEmailAddress != null) { recipient = Globals.ThisAddIn.Application.Session.CreateRecipient(item.SenderEmailAddress); addressEntry = recipient.AddressEntry; exchUser = getExchangeUser(recipient.AddressEntry); } //新規にメール作成中の場合ここ else { // 起動されたOutlookのユーザを送信者として取得 recipient = Globals.ThisAddIn.Application.Session.CurrentUser; addressEntry = recipient.AddressEntry; exchUser = getExchangeUser(addressEntry); } //個人の「連絡先」に登録されているかもしれない contactItem = null; if (addressEntry != null) { try { contactItem = addressEntry.GetContact(); } catch { contactItem = null; } } RecipientInformationDto senderInformation = null; // 送信者のExchangeUserが取得できた場合 if (exchUser != null) { senderInformation = new RecipientInformationDto(exchUser.Name, exchUser.Department, exchUser.CompanyName, FormatJobTitle(exchUser.JobTitle), Outlook.OlMailRecipientType.olOriginator); } // Exchangeアドレス帳にないが、「連絡先」にいる場合 else if (contactItem != null) { senderInformation = new RecipientInformationDto(contactItem.FullName, contactItem.Department, contactItem.CompanyName, FormatJobTitle(contactItem.JobTitle), Outlook.OlMailRecipientType.olOriginator); } // Exchangeアドレス帳にも「連絡先」にもない場合 else { string displayName; if (item.SenderName != null && !Utility.IsEmailAddress(item.SenderName)) { displayName = FormatDisplayNameAndAddress(item.SenderName, item.SenderEmailAddress); } else if (recipient != null && !Utility.IsEmailAddress(recipient.Name)) { displayName = GetDisplayNameAndAddress(recipient); } else if (addressEntry != null) { displayName = FormatDisplayNameAndAddress(addressEntry.Name, addressEntry.Address); } else { displayName = FormatDisplayNameAndAddress(item.SenderName, item.SenderEmailAddress); } senderInformation = new RecipientInformationDto(displayName, Outlook.OlMailRecipientType.olOriginator); } return(senderInformation); }
public AOMailItem(Outlook.MailItem mailItem) { OutlookMailItem = mailItem; }
public void setMailItem(Outlook.MailItem mailItem) { this.mailItem = mailItem; }
public void Populate(KPOutlookAddIn.ThisAddIn.RIBBON_TYPE showRibbon, Outlook.MailItem mail) { log = new Logger(); currMailItem = mail; const string pos = "RibbonMailRiceved.RibbonMailRiceved_Load - "; log.Info(pos + "INIT"); string pathWorkFolder = Constants.getWorkFolder(); string attachmentName = Constants.KP_ATTACHMENT_NAME; log.Info(pos + "pathWorkFolder:" + pathWorkFolder); log.Info(pos + "attachmentName:" + attachmentName); try { if (showRibbon == ThisAddIn.RIBBON_TYPE.Read) { //Disabilito il pulsante kpeople this.button1.Enabled = false; //Leggo le informazioni dall'attachment Outlook.Attachment attach = mail.Attachments[attachmentName]; if (attach != null) { //Salvo temporaneamente il file TemporaryStorage storage = new TemporaryStorage(); XmlDocument docXml = new XmlDocument(); MetadataParser parser = new MetadataParser(); docXml.Load(storage.Save(attach)); createDinamicallyRibbonFromMetadata(parser.parserMetadataSetFromXML(docXml)); storage.DeleteFolder(); } } else if (showRibbon == ThisAddIn.RIBBON_TYPE.Reply) { //Disabilito il pulsante kpeople this.button1.Enabled = true; //Leggo le informazioni dall'attachment Outlook.Attachment attach = mail.Attachments[attachmentName]; if (attach != null) { //Salvo temporaneamente il file TemporaryStorage storage = new TemporaryStorage(); XmlDocument docXml = new XmlDocument(); MetadataParser parser = new MetadataParser(); docXml.Load(storage.Save(attach)); createDinamicallyRibbonFromMetadata(parser.parserMetadataSetFromXML(docXml)); storage.DeleteFolder(); } } else { this.button1.Enabled = true; } } catch (Exception ex) { log.Error(pos + "Ex:" + ex.ToString()); } log.Info(pos + "END"); }
private void ThisAddIn_SelectionChange() { if (_myCustomTaskPane.Visible) { var NewMailSelection = new MailSelection(Application.ActiveExplorer().Selection); if ((rMailSelection == null) || (!rMailSelection.Equals(NewMailSelection))) { _mailPanel.CleanOAPanel(); rMailSelection = NewMailSelection; if (rMailSelection.Count == 1) LastSelectedMail = rMailSelection[0]; else LastSelectedMail = null; } } }
/// <summary> /// Handle the new e-mail event from main inbox /// </summary> /// <param name="Item"></param> private void Items_ItemAdd(object Item) { Outlook.MailItem mail = (Outlook.MailItem)Item; //New mail object MailParser(mail); //Process new mail for smartflow stuff }
void ThisApplication_NewMailEx(string EntryIDCollection) { if (Properties.Settings.Default.EnableNewMailNotifications) { if (EntryIDCollection != null) { string title = null; string text = null; string[] ids = EntryIDCollection.Split(','); if (ids.Length > 4) { title = "New Mail"; text = String.Format("You have {0} new messages", ids.Length); Growl.Connector.Notification notification = new Growl.Connector.Notification(this.application.Name, newmail.Name, String.Empty, title, text); Growl.Connector.CallbackContext callbackContext = new Growl.Connector.CallbackContext("null", "multimessage"); growl.Notify(notification, callbackContext); } else { foreach (string id in ids) { object obj = this.Session.GetItemFromID(id.Trim(), Type.Missing); if (obj is Outlook.MailItem) { Outlook.MailItem message = (Outlook.MailItem)obj; string body = message.Body; if (!String.IsNullOrEmpty(body)) { body = body.Replace("\r\n", "\n"); body = (body.Length > 50 ? body.Substring(0, 50) + "..." : body); } // just saving this for future reference //Outlook.MAPIFolder folder = message.Parent as Outlook.MAPIFolder; //Outlook.NameSpace outlookNameSpace = this.GetNamespace("MAPI"); //Outlook.MAPIFolder junkFolder = outlookNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders..olFolderJunk); title = message.Subject; if (!String.IsNullOrEmpty(title)) { title = title.Trim(); } title = (String.IsNullOrEmpty(title) ? "[No Subject]" : message.Subject); text = String.Format("From: {0}\n{1}", message.SenderName, body); Growl.Connector.Priority priority = Growl.Connector.Priority.Normal; if (message.Importance == Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh) { priority = Growl.Connector.Priority.High; } else if (message.Importance == Microsoft.Office.Interop.Outlook.OlImportance.olImportanceLow) { priority = Growl.Connector.Priority.Moderate; } Growl.Connector.Notification notification = new Growl.Connector.Notification(this.application.Name, newmail.Name, String.Empty, title, text); notification.Priority = priority; Growl.Connector.CallbackContext callbackContext = new Growl.Connector.CallbackContext(id, "mailmessage"); growl.Notify(notification, callbackContext); } else if (obj is Outlook.MeetingItem) { Outlook.MeetingItem message = (Outlook.MeetingItem)obj; string body = message.Body; if (!String.IsNullOrEmpty(body)) { body = body.Replace("\r\n", "\n"); body = (body.Length > 50 ? body.Substring(0, 50) + "..." : body); } title = message.Subject; if (!String.IsNullOrEmpty(title)) { title = title.Trim(); } title = (String.IsNullOrEmpty(title) ? "[No Subject]" : message.Subject); text = String.Format("From: {0}\n{1}", message.SenderName, body); Growl.Connector.Priority priority = Growl.Connector.Priority.Normal; if (message.Importance == Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh) { priority = Growl.Connector.Priority.High; } else if (message.Importance == Microsoft.Office.Interop.Outlook.OlImportance.olImportanceLow) { priority = Growl.Connector.Priority.Moderate; } Growl.Connector.Notification notification = new Growl.Connector.Notification(this.application.Name, newmail.Name, String.Empty, title, text); notification.Priority = priority; Growl.Connector.CallbackContext callbackContext = new Growl.Connector.CallbackContext(id, "mailmessage"); growl.Notify(notification, callbackContext); } } } } } }
/// <summary> /// The constructor to record the associate mailItem and register events. /// </summary> /// <param name="inspector"></param> public MailItemInspector(Outlook.Inspector inspector) : base(inspector) { _mailItem = inspector.CurrentItem as Outlook.MailItem; if (_mailItem == null) throw new Exception("Not a mailItem in the provided inspector"); ConnectEvents(); }
private void Initialise(MSOutlook.MailItem mailItem, bool bUseCache) { if (null == mailItem) throw new ArgumentNullException("mailItem"); m_oif = new OutlookIImplFactory(); m_outlookMail = mailItem; if (null == m_outlookMail) throw new ArgumentNullException("m_outlookMail"); m_RecipientsProxy = new OutlookRecipientsProxy(m_outlookMail, bUseCache); m_outlookAttachmentsProxy = new OutlookAttachmentsProxy(m_outlookMail); m_bIsValid = true; }
private void Dispose(bool disposing) { if (m_Disposed) return; m_Disposed = true; if (disposing) { } if (m_outlookAttachmentsProxy != null) { m_outlookAttachmentsProxy.Dispose(); m_outlookAttachmentsProxy = null; } if (m_outlookToRecipientsProxy != null) { m_outlookToRecipientsProxy.Dispose(); m_outlookToRecipientsProxy = null; } if (m_outlookCcRecipientsProxy != null) { m_outlookCcRecipientsProxy.Dispose(); m_outlookCcRecipientsProxy = null; } if (m_outlookBccRecipientsProxy != null) { m_outlookBccRecipientsProxy.Dispose(); m_outlookBccRecipientsProxy = null; } if (m_outlookRecipientTableProxy != null) { m_outlookRecipientTableProxy.Dispose(); m_outlookRecipientTableProxy = null; } if (m_mailItem != null) { m_mailItem.Dispose(); m_mailItem = null; } m_outlookMail = null; }
public PropertyInfo(Outlook.MailItem mailItem) { _mailItem = mailItem; }
void OutlookInspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector) { OutlookInspector = (Outlook.Inspector)Inspector; if (Inspector.CurrentItem is Outlook.MailItem) { OutlookMailItem = (Outlook.MailItem)Inspector.CurrentItem; } }