MS Outlook 2010 .SenderEmailAddress returns a huge string of characters - vba

I've searched and searched for an answer so I'll post this here. I'm trying to create a macro that will move 2 week old messages from my inbox to a specific folder I created for each of my coworkers. The macro successfully loops though all inbox message older than two weeks. However, when I use the .SenderEmailAddress it retuns a huge string of characters instead of ########.com. How do I just get the senders email address?
Without giving the exact string (security issue), here is what I get with "X"'s in place of some characters:
/o=XXXXXXX/ou=Exchange Administrative Group (XXXXXXXXXXXXXXX)/cn=Recipients/cn=XXXXX#XXXXX
At the end of the string is the Subject line text.
Any help would be greatly appreciated! :-)

This is a perfectly valid EX type address (as opposed to SMTP).
Try to use MailItem.Sender.GetExchangeUser().PrimarySmtpAddress.
You will need to check for nulls/errors of course in case the sender is not an Exchange user or if the address cannot be retrieved.

This MSDN documentation will help.

Related

multiple recipients lotusscript send

On a domino-built website I have a button that runs a lotusscript agent. Part of this agent sends emails out. Below is summary code/snippet to give you the idea of what I am doing
(only relevant lines of code):
dim sendtoString as string
dim sendtoArray as variant
sendtoString = "mailaddress1,mailaddress2" '<----- two email addresses in a string
sendtoArray = split(sendtoString,|,|)
maildoc.sendto = sendtoArray
maildoc.save(true,true) '<--- so I can look at it as a saved document
'maildoc.send(false) '<----- NOTE as of right now I am not sending, choosing to simply look at the saved version until I get this right
The strange thing is TWO documents are SAVED. I have not enabled the "send" line yet because I do not want multiple emails to be sent from the code, instead hoping the router will do this for me.
Maybe the send is going to work fine, and individuals will NOT receive multiple emails (if six email addresses are in the original string, I dont want six emails landing in each person's inbox).....and maybe I need to use the "SaveMessageOnSend" property instead.
Anyone have any insight on what is going on here?
Using LotusScript, you can generate and send email messages. When creating the email message, recipient email addresses must be assigned to the SendTo field. To send an email to a single recipient, simply set the object value to a valid email address. For example:
doc.SendTo = "someone#ibm.com"
However, when sending email to multiple recipients, you must create an array of values and append the values to the SendTo, CopyTo, or BlindCopyTo field(s). This can be achieved by building either a static or dynamic array of values.
For a full answer you can find on this blog: https://flylib.com/books/en/2.348.1/sending_email_to_multiple_recipients_using_lotusscript.html

How to recognize and pass over encrypted Email in vba outlook

I process (loop over) emails in my folders with vba procedure. in case an email is encrypted, i get the error
I want to simply ignore encrypted emails for my processing. I could do the "on error continue", but i'd prefere some
if IsEncrypted(mailitem) then
skip and go to next mailitem
end if
Can anybody help me with this?
Found it. any mailitem has the .MessageClass property, which in case of my encrypted emails is "IPM.Note.SMIME". simply checking for this string exactly answers my question
You may check the PR_SECURITY_FLAGS property value.
Const PR_SECURITY_FLAGS = "http://schemas.microsoft.com/mapi/proptag/0x6E010003"
Const SECFLAG_ENCRYPTED As Long = &H1
Dim SecFlags As Long
' Get current flags value
SecFlags = oItem.PropertyAccessor.GetProperty(PR_SECURITY_FLAGS)
Read more about that in the How to sign or encrypt a message programmatically from OOM article.
Please remember that third-party add-ins may encrypt messages without changing the message class or security flags. They will look like a regular email. In that case, you will have to parse the message body to detect them.

Search Outlook Global Address List Asynchronously

I want to;
Search the Global Address List of MS Outlook
Using an input, filterStr
To retrieve all items asynchronously that match a criteria satisfying
Contact first name starts with filterStr or contact last name starts with filterStr
Display the contacts as they become available in some sort of list
I am developing a MS Outlook add-in with Visual Studio 2017 using VB.net. (c# code examples are wellcome). I need this add-in to be able to search contacts like MS Skype for Business does, through its "Find Someone" field of "RICHEDIT60W"
I have tried the following so far;
Use "RICHEDIT60W" of MS Skype for Business (the search field) in my form
Could not find documentation
Use the "RichEdit20WPT" of MS Outlook (the "TO:" field in new e-mail compose)
Could not find documentation
Get the "Global Address List" through Session.GetGlobalAddressList
Succeeded, but looping through more than 50k items is too slow
Use the System.DirectorySearcher
This does not always work. When I'm connected to my corporate network through cable, I can create the object. When I'm connected through my home wireless, I get the error: "specified domain does not exist or could not be contacted"
I did try using a DirectoryEntry object initialized with;
name.surname.corporation.com where my e-mail address is name.surname#corporation.com, this time I get an "unspecified error"
I tried using ADODB to connect as given in https://learn.microsoft.com/en-us/windows/desktop/ad/example-code-for-searching-for-users#visual-basic-example
This also gives me an error on line 42 (root = GetObject("LDAP://rootDSE")
QUESTION: How can I do any of the following;
Get DirectorySearcher to work
Get ADODB method to work
Use the existing RichEdit controls of either Outlook or Skype for Business
?
I solved it like this;
Getting the GAL itself and the AddressEntries is fast enough, no problem there
I'm looping through the AddressEntries only once, during initialization and getting only the Nameproperties of each to a List(Of String), which takes around 3 seconds
When I need to search for an entry, I'm using Linq to query the list with IndexOf function, which takes about 150ms max to get all matches, and the items of the list are immediately accessible
This suited my needs because
- It works through my home network and even when I don't have a connection (I assume Outlook is cacheing the GAL)
- Querying using Linq is fast enough to facilitate searching as the user types
On the low (Extended MAPI - C++ or Delphi only) level, you would need to apply PR_ANR MAPI restriction: that is what Outlook uses when it resolves a name and displays the list of ambiguous matches. You can run that code on a separate thread, but it won't return matches one at a time - you will get the whole set back.
If Extended MAPI is not an option, you can use Redemption (I am its author) and its RDOSession.AddressBook.GAL.ResolveNamesEx method:
set Session = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Application.Session.MAPIOBJECT
set AdrrEntries = Session.AddressBook.GAL.ResolveNameEx("John")
Debug.Print AdrrEntries.Count & " names were returned by ResolveNameEx:"
Debug.Print "------------"
for each AE in AdrrEntries
Debug.Print AE.Name
next
Debug.Print "------------"

Forwarding mail automatically

I receive emails with subjects of the form “### auto fax” where “###” is a variable number of digits. Each of these emails must be forwarded to “####mail2fax.com”. I am looking for ideas on how to automate this.
Your addition “and it needs me to be at office” may be a problem. I am a home user of Outlook. If I want Outlook to do any while I am away, I need to leave my computer switched on. I assume you are an Outlook Exchange user. You can leave instructions that will be obeyed while you are away even if your computer is switched. However, for security reasons, the default is that you cannot leave instructions to forward an email outside your company. As I understand it, you would need to forward the “Auto fax” emails to a colleague. Since we hope to automate the process, this should not be an imposition on your colleague. You would need to create a version of your rule and macro and install it on your colleague’s computer but this should not be too difficult if my reading of this functionality is correct. The point is, that this will not be part of this answer.
A difficulty with VBA is that there are usually several ways of achieving the same effect. This does not matter if you develop your own VBA; pick your favourite way of achieving an effect and experiment until you have a full understanding of that favourite. However, if you ask for help or look for useful snippets of code, you must have a basic familiarity with every way of achieving effects because others will not share your favourite. You may find you have to get the idea of what a snippet does and then rewrite it your way. This code is written using my favourite techniques.
When you write a macro to process emails, you have two issues:
How do you select the emails you wish to process?
How do you process the selected emails?
There are four methods of selecting emails:
The user selects one or more emails and then runs the processing macro.
The macro scans one or more folders looking for emails with particular characteristics and then processes them.
You instruct Outlook to monitor a particular folder and to run a macro every time a new email arrives in that folder.
You set up a rule to select emails as the arrive and link a macro to that rule to process them.
I believe method 4 will be the easiest method to implement your requirement. However, it may not be available. It works fine on my system but apparently those responsible for an Outlook Exchange installation can forbidden it. If method 4 does not work for you, I believe method 3 will be the next best method. However, this answer will use method 1.
I use method 1 whenever I am developing a new email processing macro. If gives me total control of which emails are processed in which order. I can start with simple emails and I can run the macro against the same email again and again until I get the macro working just the way I want. Once I am satisfied with the macro, I can switch to whichever of the other methods is most appropriate.
This is the first version of my processing macro:
Public Sub ForwardAndMoveEmail(ByRef ItemCrnt As Object)
Dim FaxNum As String
Dim ItemNew As MailItem
Dim Subject As String
If ItemCrnt.Class <> olMail Then
' Ignore item if it is not an email
Exit Sub
End If
Subject = ItemCrnt.Subject
If LCase(Right$(Subject, 9)) = " auto fax" Then
‘ Only process email if the subject ends with case-insensitive " auto fax"
FaxNum = Mid$(Subject, 1, Len(Subject) - 9)
With ItemCrnt
Subject = "Fax from " & .Sender & " (" & .SenderEmailAddress & ")"
Set ItemNew = .Forward
End With
With ItemNew
.Subject = Subject
' Clear existing recipient(s)
Do While .Recipients.Count > 0
.Recipients.Remove (1)
Loop
.Recipients.Add FaxNum & "#mail2fax.com"
.Save
End With
End If
ItemCrnt.Move ItemCrnt.Parent.Parent.Folders("Faxed")
End Sub
The item to be processed is a parameter to this macro. Note that I have typed it as an Object rather than as a MailItem. Then note that the first statements of the macro checks that the item is a MailItem (Class = olMail). With method 1, the user could select something other than a MailItem. This check ensures this user error causes no problem for the macro.
Next the macro checks the Subject ends in “ auto fax” or “ Auto fax” or “ AUTO FAX” or any other variation. With method 1, the user could select the wrong MailItem. With method 3, every email is passed to the macro. Hence, the check that it is a macro to be forwarded to the fax service.
If I decided in advance which selection method I was going to use, I would not need to perform all these checks. I think that being able to change the selection method is worth the extra checks.
The macro extracts the leading characters of the Subject. I do not check that they are numeric although such a check could be added if it was important.
The macro creates a new Subject for the forwarded email. I do not know if you would want a new Subject but this demonstrates what you can do if it was helpful.
Set ItemNew = .Forward creates the item to be forwarded. Note that this statement is within a With block. This is the same as Set ItemNew = ItemCrnt.Forward.
The macro then works on ItemNew. It changes the Subject, it clears the existing recipients and adds the new one and then saves the new email as a draft.
The last statement of the macro is something else you did not ask for but which may be useful. I have created a folder named “Faxed” and I move the original email to it. This saves the original email without cluttering your Inbox.
Consider ItemCrnt.Parent.Parent.Folders("Faxed"). This is the folder to which the item is to be moved. I have chained properties together in a way that probably looks strange but is straightforward once you understand it.
ItemCrnt is the original mail item.
ItemCrnt.Parent is a property of ItemCrnt. Many objects have parents. For a MailItem it is the folder holding the MailItem; that is, folder “Inbox”.
`ItemCrnt.Parent.Parent is a property of folder “Inbox”. For a folder, its parent is the folder containing it. Since folder “Inbox” is a top-level folder, its parent is the store holding it. A “store” is a file in which Outlook stores folders, mail items, calendar items, tasks and many other things.
Having gone all the way up to the store, ItemCrnt.Parent.Parent.Folders("Faxed") goes down to a folder within the store.
The macro that calls ForwardAndMoveEmail is:
Option Explicit
Sub SelectEmailsUser()
Dim Exp As Explorer
Dim ItemCrnt As Object
Dim MailItemCrnt As Object
Set Exp = Outlook.Application.ActiveExplorer
If Exp.Selection.Count = 0 Then
Call MsgBox("Please select one or more emails then try again", vbOKOnly)
Exit Sub
End If
For Each ItemCrnt In Exp.Selection
If ItemCrnt.Class = olMail Then
Call ForwardAndMoveEmail(ItemCrnt)
End If
Next
End Sub
Don’t worry too much about this macro at this stage. Study it later when you are ready to develop your next processing email. It is a macro I wrote a long time ago. Each time I want to test a new email processing macro I simply change statement Call ForwardAndMoveEmail(ItemCrnt) to call the new macro.
This is not the final version of the processing macro although it is probably the final version of this evening. Please:
Copy the two macros to an Outlook module. The two macros can be in either order but Option Explicit must be at the top of the module.
Create folder “Faxed”. At the same level as folder “Inbox”.
Select one or more of the “Auto fax” emails and run macro SelectEmailsUser.
Check the processed “Auto fax” emails are now in folder “Faxed”.
Review the emails in folder Drafts. I think these emails are unsatisfactory. I will tell why later and what I think you should do to make them satisfactory.
Part 2
I ended the first part of this answer by saying I did not think the draft email my macro had created was satisfactory.
The problem for me is that the original email is headed up by a typical “forwarded” header: original sender, my name, date sent and subject. The author of the email has presumably spent some time creating the text of the email and would not want this irrelevant header prefixing their text. So how was I to stop this header being included in the email sent to “mail2fax.com”?
My first idea was to use method “Copy” instead of method “Forward”. This did give a satisfactory appearance but was slight awkward. With the statement Set ItemNew = ItemCrnt.Forward, ItemNew is a draft email ready to be finished and saved in folder “Drafts” or sent. But with the statement Set ItemNew = ItemCrnt.Copy, ItemNew is a received email and, when saved, is placed in folder “Inbox”. I have sent a copied email and the appearance when it arrives at one of my secondary email addresses looks satisfactory.
My second idea needs an introduction. An email can have three bodies: plain text, HTML or RTF. I have never seen an email containing a RTF (Rich Text Format) body. RTF was probably a sensible format 20 years ago if you wanted more that plain text. But today, HTML is so powerful that the same email can be rearranged for a large PC screen, a tablet or a smart phone so it is always easy to read. So for all practical purposes there are only two formats for an email: plain text and HTML. If an email has both plain text and HTML bodies, it is the HTML body that is shown to the reader. The VBA programmer can look at either or both bodies but the reader is not told that there is a plain text body. Very occasionally, I have seen a carefully constructed plain text body that has been designed for an email package that cannot handle HTML. But normally the plain text body is just the HTML body with the HTML tags stripped out.
My second idea was to use method “Forward” but then to copy the text and HTML bodies from the original email.
In the above code, you will find:
.Subject = Subject
' Clear existing recipient(s)
Please replace these two lines with:
.Subject = Subject
.Body = ItemCrnt.Body
.HtmlBody = ItemCrnt.HtmlBody
' Clear existing recipients
With this change, the draft emails will not have a “forwarded” header.
I assume you know who these emails are being faxed to. I suggest you contact one or two and say you are going to conduct an experiment. They will have already received faxes as a result of you using the keyboard interface to forward these emails. Send some of the draft emails created by my macro and ask for the recipients’ opinion on the new appearance. If they prefer the new appearance, we will be ready to move on to stage 3: Automating these emails. If they do not like the new appearance, you will need to ask them what is wrong about the new appearance and we will have to attempt to fix the problem.
Part 3
Please do not follow the instructions in this part until you are convinced that emails created by macro ForwardAndMoveEmail are as they should be. This part is about automating the process so the emails will be sent without you having any opportunity to check or correct them before they are sent.
Please make the following changes to macro ForwardAndMoveEmail:
Replace Public Sub ForwardAndMoveEmail(ByRef ItemCrnt As Object)
by Public Sub ForwardAndMoveEmail(ByRef ItemCrnt As MailItem).
With email selection method 1, it is possible (difficult but possible) to select items that are not MailItemss. I set the type of ItemCrnt to Object so this would not cause an error. To use a macro with a rule, ItemCrnt must be MailItem.
These statements are now redundant:
If ItemCrnt.Class <> olMail Then
' Ignore item if it is not an email
Exit Sub
End If
You can leave these statements since they will do no harm. Alternatively, you could delete them or place a quote in front of each statement.
Replace .Save by .Send.
On my system I can attach a macro to a rule. If you can do the same, it will be the easiest approach. However, some IT departments consider attaching a macro to a rule to be a security risk and disable it. If you find you cannot attach a macro to a rule, you will have to try the event approach. I will add additional instructions if necessary.
The screenshots below are from my home Outlook installation. You have functionality I lack so the screens you see will not be identical. However, my screenshots should be similar enough to yours to be useful.
Select one of these “auto fax” emails. From the “Home” tab click “Rules” then “Create Rule...”. You will get a pop-up window like this:
I created an “Auto fax” email in one of my secondary accounts and sent it to me main account. This is why I am shown as both the sender and the receiver. Because I had selected the “Auto fax” email, its subject is shown. Edit this subject to remove the leading digits. A tick will appear in the box next to the subject to get:
Click “Advanced Options...” to get this pop-up window:
Notice that subject in the line near the top has not been edited. This does not matter; it is the value in the “Step 2” box that matters. Note that if you click “ Auto fax” in the “Step 2” box, you can add extra values. So if some of these emails have slightly different subjects, you can add these alternative values. Click “Next” to get a pop-up window like this:
Near the bottom is “Run a script”. You will have more options and may have to scroll down to see this option. Click the box next to this option. “Run a script” will appear in the “Step 2” box. Click “Run a script” in the “Step 2” box. You will be asked to “Enable macros” if you have not done so already. A new pop-up window will appear showing all the macros that could be selected for this option. I have several possible macros so I will not show you my list. You should only see one macro: ForwardAndMoveEmail. To appear in this list, a macro must be Public and the first parameter must be a MailItem. Select ForwardAndMoveEmail if it isn’t selected and click “OK”. “Run a script” now reads “Run ForwardAndMoveEmail”. Click “Next”. You will get a pop-up window of exceptions which I assume are irrelevant to you. Click “Next” to get the final pop-up:
You can click the box against ‘Run this rule now on messages already in “Inbox”’ to forward any of “Auto fax” emails already received but not forwarded. Click “Finish”.
The “Auto fax” rule is now operational and any “Auto fax” emails will be forwarded automatically. It would be a good idea to monitor folder “Faxed” and check the intended recipients received their faxes.

Skip a line if runtime exceeds certain time limit for a single code - VBA

Im creating a form where all credentials are automatically populated by anyone who accesses it. However I am facing difficulties trying to get the user's email address.
Set olApp = CreateObject("Outlook.Application")
Set olNS = olApp.GetNamespace("MAPI")
UserEmail = olNS.CurrentUser.AddressEntry.GetExchangeUser.PrimarySmtpAddress
This one line could be taking >1 minute of some user's PC and few seconds on other's.
Is there a way to skip this if its taking more than 5 seconds for example?
I'm thinking of applying application.ontime but dont know how to go from there.
VBA is not designed for running multithreaded calls. If you want to optimize performance of your Outlook VBA solutions you may consider creating a COM add-in instead. See Chapter 12: Migrating VBA Solutions to VSTO for more information.
Before accessing the address entry object I'd suggest getting the Address property value. It returns a string representing the e-mail address of the Recipient. If it corresponds to an SMTP address then you may skip unnecessary calls.