static string GetEmailAddress(Outlook.AddressEntry entry) { string emailAddress = ""; switch (entry.AddressEntryUserType) { case Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry: case Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry: try { var user = entry.GetExchangeUser(); if (user != null) { emailAddress = user.PrimarySmtpAddress; Marshal.ReleaseComObject(user); } } catch { } break; case Outlook.OlAddressEntryUserType.olSmtpAddressEntry: emailAddress = entry.Address; break; } return(emailAddress); }
// RopModifyRules RopGetRulesTable public void CreateNewRule() { Outlook.AddressEntry currentUser = oApp.Session.CurrentUser.AddressEntry; Outlook.ExchangeUser manager = currentUser.GetExchangeUser(); Outlook.Rules rules = oApp.Session.DefaultStore.GetRules(); if (manager != null) { string displayName = manager.Name; int num = rules.Count; Outlook.Rule rule = rules.Create(displayName + "_" + num, Outlook.OlRuleType.olRuleReceive); // Rule conditions: From condition rule.Conditions.From.Recipients.Add(manager.PrimarySmtpAddress); rule.Conditions.From.Recipients.ResolveAll(); rule.Conditions.From.Enabled = true; // Sent only to me rule.Conditions.ToMe.Enabled = true; // Rule actions: MarkAsTask action rule.Actions.MarkAsTask.MarkInterval = Outlook.OlMarkInterval.olMarkToday; rule.Actions.MarkAsTask.FlagTo = "Follow-up"; rule.Actions.MarkAsTask.Enabled = true; try { rules.Save(true); } catch (Exception e) { throw new Exception(e.Message); } bool result = MessageParser.ParseMessage(); Assert.IsTrue(result, "Case failed, check the details information in error.txt file."); } }
public void GetCurrentUserMembership(DataGridView dgv) { Outlook.AddressEntry currentUser = app.Session.CurrentUser.AddressEntry; if (currentUser.Type == "EX") { Outlook.ExchangeUser exchUser = currentUser.GetExchangeUser(); if (exchUser != null) { Outlook.AddressEntries addrEntries = exchUser.GetMemberOfList(); if (addrEntries != null) { foreach (Outlook.AddressEntry addrEntry in addrEntries) { DataGridViewRow dgvr = new DataGridViewRow(); dgvr.CreateCells(dgv); dgvr.Cells[0].Value = addrEntry.Name; dgvr.Cells[1].Value = addrEntry.Address; dgv.Rows.Add(dgvr); } } } } }
public string laydiachimail(Outlook.Account account) { try { if (string.IsNullOrEmpty(account.SmtpAddress) || string.IsNullOrEmpty(account.UserName)) { Outlook.AddressEntry oAE = account.CurrentUser.AddressEntry as Outlook.AddressEntry; if (oAE.Type == "EX") { Outlook.ExchangeUser oEU = oAE.GetExchangeUser() as Outlook.ExchangeUser; return(oEU.PrimarySmtpAddress); } else { return(oAE.Address); } } else { return(account.SmtpAddress); } } catch (Exception ex) { ghiloi.WriteLogError(ex); return(""); } }
public string[] getAddresses(int index) { string[] addressesArr = null; // 保存邮件组下的成员地址 if (this.addressList[index] is Outlook.DistListItem) { Outlook.DistListItem distListItem = (Outlook.DistListItem) this.addressList[index]; addressesArr = new string[distListItem.MemberCount]; for (int i = 0; i < distListItem.MemberCount; i++) { Outlook.Recipient recipient = distListItem.GetMember(i + 1); addressesArr[i] = recipient.Name + " " + recipient.Address; } } else if (this.addressList[index] is Outlook.AddressEntries) { Outlook.AddressEntries addresses = (Outlook.AddressEntries) this.addressList[index]; addressesArr = new string[addresses.Count]; for (int i = 1; i <= addresses.Count; i++) { Outlook.AddressEntry membAddress = addresses[i]; addressesArr[i - 1] = membAddress.Name + " " + membAddress.GetExchangeUser().PrimarySmtpAddress; } } return(addressesArr); }
/* Método compartilhado entre os demais, que envia os emails, conforme título, destinatários, corpo de texto e anexos desejados */ public void SendEmail(string title, string[] recipients, string body, string[] attachments = null) { Outlook.Application app = new Outlook.Application(); Outlook.MailItem mail = app.CreateItem(Outlook.OlItemType.olMailItem); mail.Subject = title; Outlook.AddressEntry currentUser = app.Session.CurrentUser.AddressEntry; if (currentUser.Type == "EX") { Outlook.ExchangeUser manager = currentUser.GetExchangeUser().GetExchangeUserManager(); foreach (var nome in recipients) { mail.Recipients.Add(nome); } mail.Recipients.ResolveAll(); mail.HTMLBody = body + currentUser.Name.ToString() + "</ body ></ html >"; if (attachments != null) { foreach (var atch in attachments) { mail.Attachments.Add(atch, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing); } } mail.Send(); } }
// Retrieves the email address for a given account object static string EnumerateAccountEmailAddress(Outlook.Account account) { try { if (string.IsNullOrEmpty(account.SmtpAddress) || string.IsNullOrEmpty(account.UserName)) { Outlook.AddressEntry oAE = account.CurrentUser.AddressEntry as Outlook.AddressEntry; if (oAE.Type == "EX") { Outlook.ExchangeUser oEU = oAE.GetExchangeUser() as Outlook.ExchangeUser; return(oEU.PrimarySmtpAddress); } else { return(oAE.Address); } } else { return(account.SmtpAddress); } } catch (Exception ex) { Console.WriteLine(ex.Message); return(""); } }
private bool RecipientContainsString(Outlook.Recipient recipient, string name) { Outlook.AddressEntry addressEntry = recipient.AddressEntry; if (addressEntry == null) { return(false); } if (addressEntry.Name.ContainsWholeWord(name, ignoreCase: true)) { return(true); } Outlook.ContactItem contact = addressEntry.GetContact(); if (contact != null) { string email = contact.Email1Address; if (email != null && email.ContainsWholeWord(name, ignoreCase: true)) { return(true); } email = contact.Email2Address; if (email != null && email.ContainsWholeWord(name, ignoreCase: true)) { return(true); } email = contact.Email3Address; if (email != null && email.ContainsWholeWord(name, ignoreCase: true)) { return(true); } string fullName = contact.FullName; if (fullName != null && fullName.ContainsWholeWord(name, ignoreCase: true)) { return(true); } } Outlook.ExchangeUser exchageUser = addressEntry.GetExchangeUser(); if (exchageUser != null) { string alias = exchageUser.Alias; if (alias.ContainsWholeWord(name, ignoreCase: true)) { return(true); } string primarySmptAddress = exchageUser.PrimarySmtpAddress; if (primarySmptAddress.ContainsWholeWord(name, ignoreCase: true)) { return(true); } } return(false); }
// ª[’ljÁ]“Y•tƒtƒ@ƒCƒ‹ƒvƒƒpƒeƒBƒ`ƒFƒbƒN‹@”\ private string GetSMTPAddressOfExchangeUser(OL.MailItem mail) { return(mail.SenderEmailAddress); //MessageBox.Show(mail.SenderEmailAddress); /* * const uint PR_SMTP_ADDRESS = 0x39FE001E; * * MAPI.SessionClass objSession = new MAPI.SessionClass(); * objSession.MAPIOBJECT = recipient.Application.Session.MAPIOBJECT; * MAPI.AddressEntry addEntry = (MAPI.AddressEntry)objSession.GetAddressEntry(recipient.EntryID); * MAPI.Field field = (MAPI.Field)((MAPI.Fields)addEntry.Fields).get_Item(PR_SMTP_ADDRESS, null); * * return field.Value.ToString(); */ string PR_SMTP_ADDRESS = @"http://schemas.microsoft.com/mapi/proptag/0x39FE001E"; if (mail == null) { throw new ArgumentNullException(); } if (mail.SenderEmailType == "EX") { OL.AddressEntry sender = mail.Sender; if (sender != null) { //Now we have an AddressEntry representing the Sender if (sender.AddressEntryUserType == OL.OlAddressEntryUserType.olExchangeUserAddressEntry || sender.AddressEntryUserType == OL.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) { //Use the ExchangeUser object PrimarySMTPAddress OL.ExchangeUser exchUser = sender.GetExchangeUser(); if (exchUser != null) { return(exchUser.PrimarySmtpAddress); } else { return(null); } } else { return(sender.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS) as string); } } else { return(null); } } else { return(mail.SenderEmailAddress); } }
/// <summary> /// AddressEntryを元にxchangeUserオブジェクトを取得する /// </summary> /// <param name="entry">AddressEntryオブジェクト</param> /// <returns>AddressEntryに紐づいたExchangeUserオブジェクト。失敗した場合はnullを返す。</returns> private static Outlook.ExchangeUser getExchangeUser(Outlook.AddressEntry entry) { Outlook.ExchangeUser exchUser; try { exchUser = entry.GetExchangeUser(); } catch (Exception) { exchUser = null; } return(exchUser); }
public static string GetSenderSMTPAddress(Outlook.MailItem mail) { string PR_SMTP_ADDRESS = @"http://schemas.microsoft.com/mapi/proptag/0x39FE001E"; if (mail == null) { throw new ArgumentNullException(); } if (mail.SenderEmailType == "EX") { Outlook.AddressEntry sender = mail.Sender; if (sender != null) { //Now we have an AddressEntry representing the Sender if (sender.AddressEntryUserType == Outlook.OlAddressEntryUserType. olExchangeUserAddressEntry || sender.AddressEntryUserType == Outlook.OlAddressEntryUserType. olExchangeRemoteUserAddressEntry) { //Use the ExchangeUser object PrimarySMTPAddress Outlook.ExchangeUser exchUser = sender.GetExchangeUser(); if (exchUser != null) { return(exchUser.PrimarySmtpAddress); } else { return(null); } } else { return(sender.PropertyAccessor.GetProperty( PR_SMTP_ADDRESS) as string); } } else { return(null); } } else { return(mail.SenderEmailAddress); } }
private void ProcessExchangeUser(Outlook.AddressEntry address) { if (Globals.ThisAddIn.Offline) { var contact = address.GetContact(); if (contact != null) { ProcessContact(contact); return; } } ProcessExchangeUser(address.GetExchangeUser()); }
private void ThisAddIn_Startup(object sender, System.EventArgs e) { // Initialize variables m_Application = this.Application; m_Explorers = m_Application.Explorers; m_Inspectors = m_Application.Inspectors; m_Windows = new List <OutlookExplorer>(); m_InspectorWindows = new List <OutlookInspector>(); // Wire up event handlers to handle multiple Explorer windows m_Explorers.NewExplorer += new Outlook.ExplorersEvents_NewExplorerEventHandler( m_Explorers_NewExplorer); // Wire up event handlers to handle multiple Inspector windows m_Inspectors.NewInspector += new Outlook.InspectorsEvents_NewInspectorEventHandler( m_Inspectors_NewInspector); // Add the ActiveExplorer to m_Windows Outlook.Explorer expl = m_Application.ActiveExplorer() as Outlook.Explorer; OutlookExplorer window = new OutlookExplorer(expl); m_Windows.Add(window); // Hook up event handlers for window window.Close += new EventHandler(WrappedWindow_Close); window.InvalidateControl += new EventHandler < OutlookExplorer.InvalidateEventArgs>( WrappedWindow_InvalidateControl); // Get IPictureDisp for CurrentUser on startup try { Outlook.AddressEntry addrEntry = Globals.ThisAddIn.Application.Session.CurrentUser.AddressEntry; if (addrEntry.Type == "EX") { Outlook.ExchangeUser exchUser = addrEntry.GetExchangeUser() as Outlook.ExchangeUser; m_pictdisp = exchUser.GetPicture() as stdole.IPictureDisp; } } catch (Exception ex) { //Write exception to debug window Debug.WriteLine(ex.Message); } }
//Получает все учетные записи с почты. private void EnumerateGAL() { try { Outlook.Application app = new Outlook.Application(); Outlook.NameSpace ns = app.GetNamespace("MAPI"); ns.Logon("", "", false, true); Outlook.AddressList gal = ns.Session.GetGlobalAddressList(); progressBar1.Maximum = gal.AddressEntries.Count; if (gal != null) { int n = 1; for (int i = 1; i <= gal.AddressEntries.Count; i++) { Outlook.AddressEntry addrEntry = gal.AddressEntries[i]; if (addrEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry || addrEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) { Outlook.ExchangeUser exchUser = addrEntry.GetExchangeUser(); Program.UpdataUsers.Add(exchUser.Name, exchUser.PrimarySmtpAddress); progressBar1.Value = i; } #region один логин выпадает там //if (addrEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeDistributionListAddressEntry) //{ // Outlook.ExchangeDistributionList exchDL = addrEntry.GetExchangeDistributionList(); // //MessageBox.Show(exchDL.Name + " " + exchDL.PrimarySmtpAddress); // using (StreamWriter sw = new StreamWriter(nameUsers2, true, System.Text.Encoding.Default)) // { // sw.WriteLine("2 file: " + exchDL.Name + " - " + exchDL.PrimarySmtpAddress); // } // progressBar1.Value = i; //} #endregion n++; } if (n > gal.AddressEntries.Count) { progressBar1.Value = 0; } Close(); } } catch (Exception e) { MessageBox.Show(e.Message); } }
internal static string DefaultEmailAddress() { string defaultAddress = ""; try { Outlook.Recipient user = Globals.ThisAddIn._nameSpace.CurrentUser; Outlook.AddressEntry ae = user.AddressEntry; if ((ae.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry) || (ae.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)) { Outlook.ExchangeUser exUser = ae.GetExchangeUser(); if (exUser != null) { defaultAddress = exUser.PrimarySmtpAddress; if (String.IsNullOrEmpty(defaultAddress)) { defaultAddress = ae.Address; } exUser = null; } else { defaultAddress = ae.Address; } } else { defaultAddress = ae.Address; } ae = null; user = null; } catch { defaultAddress = ""; } return(defaultAddress); }
/// <summary> /// Get a best approximation of the username of the current user. /// </summary> /// <returns>a best approximation of the username of the current user</returns> public static string GetCurrentUsername() { string result; Outlook.Recipient currentUser = Globals.ThisAddIn.Application.Session.CurrentUser; Outlook.AddressEntry addressEntry = currentUser.AddressEntry; if (addressEntry.Type == "EX") { result = addressEntry.GetExchangeUser().Name; } else { result = currentUser.Name; // result = addressEntry.Address.Substring(0, addressEntry.Address.IndexOf('@')); } return(result); }
public static void DisplayGlobalAddressList() { DataTable table = new DataTable(); table.Columns.Add("Name", typeof(string)); table.Columns.Add("Company", typeof(string)); table.Columns.Add("Address", typeof(string)); Outlook.Application outlook = new Outlook.Application(); Outlook.AddressList gal = outlook.Session.GetGlobalAddressList(); if (gal != null) { for (int i = 1; i < gal.AddressEntries.Count - 1; i++) { try { Outlook.AddressEntry addressEntry = gal.AddressEntries[i]; if (addressEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry || addressEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) { Outlook.ExchangeUser exUser = addressEntry.GetExchangeUser(); Debug.WriteLine(exUser.Name + " " + exUser.CompanyName); table.Rows.Add(exUser.Name, exUser.CompanyName, exUser.PrimarySmtpAddress); } if (addressEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeDistributionListAddressEntry) { Outlook.ExchangeDistributionList exList = addressEntry.GetExchangeDistributionList(); Debug.WriteLine(exList.Name + " " + exList.PrimarySmtpAddress); table.Rows.Add(exList.Name, "", ""); } } catch { continue; } } } ExportCsvUtil.ExportCsv(table, "", ""); }
private string GetSenderAddress(Outlook.MailItem mail) { if (mail == null) { return(null); } if (mail.SenderEmailType == "EX") { Outlook.AddressEntry sender = mail.Sender; if (sender != null) { //Now we have an AddressEntry representing the Sender if (sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry || sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) { //Use the ExchangeUser object PrimarySMTPAddress Outlook.ExchangeUser exchUser = sender.GetExchangeUser(); if (exchUser != null) { return(exchUser.PrimarySmtpAddress); } else { return(null); } } else { return(sender.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS) as string); } } else { return(null); } } else { return(mail.SenderEmailAddress); } }
private static string getSenderEmailAddress(Outlook.MailItem mail) { Outlook.AddressEntry sender = mail.Sender; string SenderEmailAddress = ""; if (sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry || sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) { Outlook.ExchangeUser exchUser = sender.GetExchangeUser(); if (exchUser != null) { SenderEmailAddress = exchUser.PrimarySmtpAddress; } } else { SenderEmailAddress = mail.SenderEmailAddress; } return(SenderEmailAddress); }
/// <summary> /// Get the SMTP address implied by this AddressEntry object /// </summary> /// <remarks> /// This is different from RecipientExtension.GetSmtpAddress because /// we don't have access to anything equivalent to a Recipient object. /// </remarks> /// <see cref="RecipientExtensions.GetSmtpAddress(Outlook.Recipient)"/> /// <param name="entry">the AddressEntry</param> /// <returns>The SMTP address, if it can be recovered, else the empty string.</returns> public static string GetSmtpAddress(this Outlook.AddressEntry entry) { string result; try { result = smtpAddressCache[entry]; } catch (KeyNotFoundException) { result = string.Empty; } if (string.IsNullOrEmpty(result)) { try { switch (entry.AddressEntryUserType) { case Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry: case Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry: Outlook.ExchangeUser exchUser = entry.GetExchangeUser(); result = exchUser == null ? string.Empty : exchUser.PrimarySmtpAddress; break; default: result = entry.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS) as string; break; } } catch (Exception any) { ErrorHandler.Handle("Failed while trying to obtain an SMTP address", any); } } smtpAddressCache[entry] = result; return(result); }
private static string GetSMTPAddress(Outlook.AddressEntry entry) { Debug.Assert(entry != null); if (entry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeAgentAddressEntry || entry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) { Outlook.ExchangeUser exchUser = entry.GetExchangeUser(); if (exchUser != null) { return(exchUser.PrimarySmtpAddress); } else { return(null); } } else { string PR_SMTP_ADDRESS = @"http://schemas.microsoft.com/mapi/proptag/0x39FE001E"; return(entry.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS) as string); } }
bool IRepositoryItemFactory.Send_Outlook(bool actualSend, string MailTo, string Event, string Subject, string Body, string MailCC, List <string> Attachments, List <KeyValuePair <string, string> > EmbededAttachment) { try { Outlook.Application objOutLook = null; if (string.IsNullOrEmpty(MailTo)) { Event = "Failed: Please provide TO email address."; return(false); } if (string.IsNullOrEmpty(Subject)) { Event = "Failed: Please provide email subject."; return(false); } // Check whether there is an Outlook process running. if (System.Diagnostics.Process.GetProcessesByName("OUTLOOK").Count() > 0) { // If so, use the GetActiveObject method to obtain the process and cast it to an ApplicatioInstall-Package Microsoft.Office.Interop.Exceln object. objOutLook = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application; } else { // If not, create a new instance of Outlook and log on to the default profile. objOutLook = new Outlook.Application(); Outlook.NameSpace nameSpace = objOutLook.GetNamespace("MAPI"); nameSpace.Logon("", "", System.Reflection.Missing.Value, System.Reflection.Missing.Value); nameSpace = null; } mOutlookMail = objOutLook.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem; mOutlookMail.HTMLBody = Body; mOutlookMail.Subject = Subject; Outlook.AddressEntry currentUser = objOutLook.Session.CurrentUser.AddressEntry; if (currentUser.Type == "EX") { Outlook.ExchangeUser manager = currentUser.GetExchangeUser(); // Add recipient using display name, alias, or smtp address string emails = MailTo; Array arrEmails = emails.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string email in arrEmails) { mOutlookMail.Recipients.Add(email); } //Add CC if (!String.IsNullOrEmpty(MailCC)) { Array arrCCEmails = MailCC.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string MailCC1 in arrCCEmails) { mOutlookMail.Recipients.Add(MailCC1); } } mOutlookMail.Recipients.ResolveAll(); mOutlookMail.CC = MailCC; mOutlookMail.To = MailTo; //Add Attachment foreach (string AttachmentFileName in Attachments) { if (String.IsNullOrEmpty(AttachmentFileName) == false) { mOutlookMail.Attachments.Add(AttachmentFileName, Type.Missing, Type.Missing, Type.Missing); } } //attachment which is embeded into the email body(images). foreach (KeyValuePair <string, string> AttachmentFileName in EmbededAttachment) { if (String.IsNullOrEmpty(AttachmentFileName.Key) == false) { if (System.IO.File.Exists(AttachmentFileName.Key)) { Outlook.Attachment attachment = mOutlookMail.Attachments.Add(AttachmentFileName.Key, Outlook.OlAttachmentType.olEmbeddeditem, null, ""); attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", AttachmentFileName.Value); } } } if (actualSend) { //Send Mail mOutlookMail.Send(); } } return(true); } catch (Exception ex) { if (ex.Message.Contains("Mailbox Unavailabel")) { Event = "Failed: Please provide correct sender email address"; } else if (ex.StackTrace.Contains("System.Runtime.InteropServices.Marshal.GetActiveObject")) { Event = "Please make sure ginger/outlook opened in same security context (Run as administrator or normal user)"; } else if (ex.StackTrace.Contains("System.Security.Authentication.AuthenticationException") || ex.StackTrace.Contains("System.Net.Sockets.SocketException")) { Event = "Please check SSL configuration"; } else { Event = "Failed: " + ex.Message; } return(false); } }
private static string GetOutlookEmailAddress(Outlook.ContactItem outlookContactItem, string emailAddressType, string emailEntryID, string emailAddress) { switch (emailAddressType) { case "EX": // Microsoft Exchange address: "/o=xxxx/ou=xxxx/cn=Recipients/cn=xxxx" Outlook.NameSpace outlookNameSpace = outlookContactItem.Application.GetNamespace("mapi"); try { // The emailEntryID is garbage (bug in Outlook 2007 and before?) - so we cannot do GetAddressEntryFromID(). // Instead we create a temporary recipient and ask Exchange to resolve it, then get the SMTP address from it. //Outlook.AddressEntry addressEntry = outlookNameSpace.GetAddressEntryFromID(emailEntryID); Outlook.Recipient recipient = outlookNameSpace.CreateRecipient(emailAddress); try { recipient.Resolve(); if (recipient.Resolved) { Outlook.AddressEntry addressEntry = recipient.AddressEntry; if (addressEntry != null) { try { if (addressEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry) { Outlook.ExchangeUser exchangeUser = addressEntry.GetExchangeUser(); if (exchangeUser != null) { try { return(exchangeUser.PrimarySmtpAddress); } finally { Marshal.ReleaseComObject(exchangeUser); } } } else { Logger.Log(string.Format("Unsupported AddressEntryUserType {0} for contact '{1}'.", addressEntry.AddressEntryUserType, outlookContactItem.FileAs), EventType.Debug); } } finally { Marshal.ReleaseComObject(addressEntry); } } } } finally { if (recipient != null) { Marshal.ReleaseComObject(recipient); } } } catch (Exception ex) { // Fallback: If Exchange cannot give us the SMTP address, we give up and use the Exchange address format. // TODO: Can we do better? Logger.Log(string.Format("Error getting the email address of outlook contact '{0}' from Exchange format '{1}': {2}", outlookContactItem.FileAs, emailAddress, ex.Message), EventType.Warning); return(emailAddress); } finally { if (outlookNameSpace != null) { Marshal.ReleaseComObject(outlookNameSpace); } } // Fallback: If Exchange cannot give us the SMTP address, we give up and use the Exchange address format. // TODO: Can we do better? return(emailAddress); case "SMTP": default: return(emailAddress); } }
internal static string GetSenderSMTPAddress(this Outlook.MailItem _mail) { if (_mail == null) { throw new ArgumentNullException(); } if (_mail.SenderEmailType == "EX") { Outlook.AddressEntry sender = null; try { sender = _mail.Sender; if (sender != null) { //Now we have an AddressEntry representing the Sender if (sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry || sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry) { //Use the ExchangeUser object PrimarySMTPAddress Outlook.ExchangeUser exchUser = null; try { exchUser = sender.GetExchangeUser(); if (exchUser != null) { return(exchUser.PrimarySmtpAddress); } else { return(null); } } finally { if (exchUser != null) { Marshal.ReleaseComObject(exchUser); exchUser = null; } } } else { Outlook.PropertyAccessor propertyAccessor = null; try { propertyAccessor = sender.PropertyAccessor; if (propertyAccessor != null) { try { return(propertyAccessor.GetProperty(PR_SMTP_ADDRESS) as string); } catch (COMException) { } } } finally { if (propertyAccessor != null) { Marshal.ReleaseComObject(propertyAccessor); propertyAccessor = null; } } } } else { return(null); } } finally { if (sender != null) { Marshal.ReleaseComObject(sender); sender = null; } } } else { return(_mail.SenderEmailAddress); } return(_mail.SenderEmailAddress); }
public static string GetOutlookEmailAddress(string subject, Outlook.Recipient recipient) { string emailAddress = recipient.Address != null ? recipient.Address : recipient.Name; switch (recipient.AddressEntry.AddressEntryUserType) { case Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry: // Microsoft Exchange address: "/o=xxxx/ou=xxxx/cn=Recipients/cn=xxxx" try { // The emailEntryID is garbage (bug in Outlook 2007 and before?) - so we cannot do GetAddressEntryFromID(). // Instead we create a temporary recipient and ask Exchange to resolve it, then get the SMTP address from it. //Outlook.AddressEntry addressEntry = outlookNameSpace.GetAddressEntryFromID(emailEntryID); //try //{ recipient.Resolve(); if (recipient.Resolved) { Outlook.AddressEntry addressEntry = recipient.AddressEntry; if (addressEntry != null) { try { if (addressEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry) { Outlook.ExchangeUser exchangeUser = addressEntry.GetExchangeUser(); if (exchangeUser != null) { try { return(exchangeUser.PrimarySmtpAddress); } finally { Marshal.ReleaseComObject(exchangeUser); } } } else { Logger.Log(string.Format("Unsupported AddressEntryUserType {0} for email '{1}' in appointment '{2}'.", addressEntry.AddressEntryUserType, addressEntry.Address, subject), EventType.Debug); } } finally { Marshal.ReleaseComObject(addressEntry); } } } //} //finally //{ // if (recipient != null) // Marshal.ReleaseComObject(recipient); //} } catch (Exception ex) { // Fallback: If Exchange cannot give us the SMTP address, we give up and use the Exchange address format. // TODO: Can we do better? Logger.Log(string.Format("Error getting the email address of outlook appointment '{0}' from Exchange format '{1}': {2}", subject, emailAddress, ex.Message), EventType.Warning); return(emailAddress); } // Fallback: If Exchange cannot give us the SMTP address, we give up and use the Exchange address format. // TODO: Can we do better? return(emailAddress); case Outlook.OlAddressEntryUserType.olSmtpAddressEntry: default: return(emailAddress); } }
public void showAddress(string searchName, Outlook.AddressEntry address, int flag) { if (address != null) { // 邮件地址 if (address.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry) // 普通地址 { // 普通地址的 searchName 中缺少Email地址 需要另外获取 this.showSingle(this.i18n[this.lang]["mailAddress"] + ": " + searchName + " " + address.GetExchangeUser().PrimarySmtpAddress, flag); } else if (address.AddressEntryUserType == Outlook.OlAddressEntryUserType.olOutlookContactAddressEntry) // 存入联系人中的地址 { // 存入联系人中的地址的 searchName 中包含了Email地址 无要另外获取 this.showSingle(this.i18n[this.lang]["mailAddress"] + ": " + searchName, flag); } // 组邮件地址 else if (address.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeDistributionListAddressEntry) // 普通组地址 { // 普通组地址的 searchName 为组名 Email地址可通过Outlook ExchangeDistributionList 对象获取 Outlook.ExchangeDistributionList disList = address.GetExchangeDistributionList(); this.showMuilt(this.i18n[this.lang]["groupMailAddress"] + ": " + searchName + " " + disList.PrimarySmtpAddress, flag); this.addAddressNativeGroupList(disList); } else if (address.AddressEntryUserType == Outlook.OlAddressEntryUserType.olOutlookDistributionListAddressEntry) // 自建组地址 { // 自建组地址的 searchName 为组名 且无Email地址 直接仅显示组名 this.showMuilt(this.i18n[this.lang]["groupMailAddress"] + ": " + searchName, flag); this.addAddressSelfBuildGroupList(address, searchName); } } else { this.showSingle(searchName, 0); } }
private void button1_Click(object sender, RibbonControlEventArgs e) { var m = e.Control.Context as Inspector; var mailitem = m.CurrentItem as MailItem; if (mailitem != null) { if (mailitem.Attachments.Count > 0) { try { string socServer = Settings1.Default.server; var cred = CredentialManager.ReadCredential("PhishPhinder Outlook"); string socUser = cred.UserName; string socPass = cred.Password; //Configure session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = socServer, PortNumber = 990, UserName = socUser, Password = socPass, FtpSecure = FtpSecure.Implicit, }; using (Session session = new Session()) { try { // Connect session.Open(sessionOptions); // Upload files foreach (Microsoft.Office.Interop.Outlook.Attachment item in mailitem.Attachments) { item.SaveAsFile(Path.Combine(@"c:\temp", item.FileName)); var uploadFile = (Path.Combine(@"c:\temp", item.FileName)); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; session.PutFiles(uploadFile, "/", false, transferOptions); using (var msg = new MsgReader.Outlook.Storage.Message(Path.Combine(@"c:\temp", item.FileName))) { var from = msg.Sender; var sentOn = msg.SentOn; string subject = msg.Subject; Microsoft.Office.Interop.Outlook.Application cApp = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.MailItem SOCemail = cApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); SOCemail.Subject = "Phish reported to SOC"; SOCemail.Body = $"The following message has been uploaded to the SOC FTPS server for review:\n\nSubject: \"{subject}\"\nSent On: \"{sentOn}\"".Replace("\n", Environment.NewLine); SOCemail.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh; Microsoft.Office.Interop.Outlook.AddressEntry cUser = cApp.Session.CurrentUser.AddressEntry; Microsoft.Office.Interop.Outlook.ExchangeUser cmanager = cUser.GetExchangeUser().GetExchangeUserManager(); SOCemail.Recipients.Add("*****@*****.**"); SOCemail.Recipients.Add("*****@*****.**"); SOCemail.Recipients.ResolveAll(); SOCemail.Send(); } File.Delete(Path.Combine(@"c:\temp", item.FileName)); } MessageBox.Show("This phish has been reported to the SOC"); session.Close(); } //Catch connection failures catch (System.Exception ex) { MessageBox.Show("Connection failed. Please check your username and password."); } } } catch (System.NullReferenceException ex1) { MessageBox.Show("Please populate your settings before continuing."); } } else { //Thrown if there are no attachments MessageBox.Show("This ain't no phish!"); } } }