Accessing outlook message body with excel vba: error 287 - excel

We have a lot of emails saved to a folder on the file system to be processed by extracting text from the message bodies. Office 2010.
Dim app As Object
Dim msg As Object
dim msg_body as string
Set app = New Outlook.Application
Set msg = app.CreateItemFromTemplate("c:\path\to\message.msg")
msg_body = msg.body
This code works fine on my laptop however when I use it on the work network it gives error '287'.
While debugging I noticed that I can view msg msg.display and even change the body with msg.body = "some text". However I cannot read the message body. Also tried msg.HTMLbody which could not be read.

The most probable cause is your company's policies.
Check this registry key to solve the SaveAs (change the 16 to your office version).
hkcu\software\policies\microsoft\office\16.0\outlook\security\promptoomsaveas
You can change the value to 2, or ask your system administrator to create a new GPO.
More information on this and other security configurations in:
https://support.microsoft.com/en-za/help/926512/information-for-administrators-about-e-mail-security-settings-in-outlo

Related

Extract attachments from email and email them as attachments using win32com.client in Python

I am trying to loop through email messages in Outlook using python and get all the attachments in each email, extract them and send them to a different person if it meets a certain criteria. Currently I am saving the attachment and re-attaching it while sending an email. Is there any way where I can do this dynamically and not save the file in the first place
Here is what I have:
import os
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
first_msg = messages.GetFirst()
attachments = first_msg.Attachments
attachment = attachments[0]
attachment.SaveAsFile(os.getcwd()+'\\'+attachment.filename)
Outlook = win32com.client.Dispatch("Outlook.Application")
mail = Outlook.CreateItem(0)
mail.To = 'email#test.com'
mail.Subject = 'This is a sample'
attachment = mail.Attachments.Add(myfolder/file.pdf)
mail.Body = 'Sending an attachment through email using python'
mail.Send()
Is there a method where I can bypass saving the file and send the attached file directly?
The Outlook object model doesn't provide any method or property for dealing with attachments on the fly (without saving them to a disk). The Attachment.SaveAsFile method which saves the attachment to the specified path is exactly what you need.
On the other side you may consider a low-level API on which Outlook is built on - Extended MAPI. It allows opening getting property values with streams without saving them to the disk. The PR_ATTACH_DATA_BIN property holds the attachment when the value of the PR_ATTACH_METHOD property is ATTACH_BY_VALUE, which is the usual attachment method and the only one required to be supported. PR_ATTACH_DATA_BIN also holds an OLE 1.0 OLESTREAM attachment when the value of PR_ATTACH_METHOD is ATTACH_OLE. See Opening an attachment for more information.
Not in the Outlook Object Model - saving the attachment as file (if it is a regular olByValue attachment) and reattaching it is your only option. You can attach the whole original message as an attachment though by passing a MailItem object as an argument to Attachments.Add: that will create an embedded message attachment.
As Eugene suggested, you can use Extended MAPI (C++ or Delphi), but it is not accessible in Python. If using Redemption is an option (I am its author), it allows to pass one attachment (RDOAttachment) as an argument to RDOMail.Attachments.Add without saving as file first. That will work for all types of attachments (olByValue, olOLE, olEmbeddedItem, etc.)

Sending Massive emails on excel vba, OLE issue

I hope you're doing great.
I'm using this code to send emails in VBA Excel, but it only works one time, then I have to close Outlook on Task manager. If I don't do this, I get a message that says "Microsoft Excel is waiting for another application to complete an OLE action". The only thing I have to do is close the outlook app on the task manager, and then it works perfectly fine.
Could you please help me fix this issue please? Below I'll post my code
Dim email As Outlook.MailItem
Dim direc As String
Dim body As String
Set A = New Outlook.Application
For i = 2 To ActiveSheet.Cells(Rows.Count, 16).End(xlUp).Row
direc = Worksheets("NewSheet").Cells(i, 16).Value
Set email = A.CreateItem(emailItem)
With email
direc = Worksheets("NewSheet").Cells(i, 16).Value
If (direc <> "0") Then
.To = direc
.Subject = "Notification Test"
body = Worksheets("NewSheet").Cells(i, 14)
.HTMLBody = "<HTML><BODY style=font-size:11pt;font-family:Calibri>This is a notification reminder to let you know that you have <b>" & body & "</b> open contact(s) that you must Update</BODY><br><br>Best Regards, </br></br><br> Anonymous </br></HTML>"
.Display
.Send
End If
End With
Next i
Thank you so much for your time and help.
Do not call both Display and Send. Get rid of the Display line.
I'd suggest trying to run the code in Outlook VBA environment to make sure the issue is not related to security issues when sending emails. The fact is that the Outlook object model generates security issues or give security prompts to users when protected properties or methods are called using automation. Or just may try to call Save instead of Send in the following way:
Set email = A.CreateItem(emailItem)
With email
direc = Worksheets("NewSheet").Cells(i, 16).Value
If (direc <> "0") Then
.To = direc
.Subject = "Notification Test"
body = Worksheets("NewSheet").Cells(i, 14)
.HTMLBody = "<HTML><BODY style=font-size:11pt;font-family:Calibri>This is a notification reminder to let you know that you have <b>" & body & "</b> open contact(s) that you must Update</BODY><br><br>Best Regards, </br></br><br> Anonymous </br></HTML>"
.Save
End If
End With
Next i
If this code works correctly than a security issue is the case.
The Send method may fire an exception when you try to automate Outlook. In this case most probably you are faced with an Outlook security issue. It can also be a prompt issued by Outlook if you try to access any protected property or method. But in your case that can be an exception or error. You get the security prompts/exceptions because Outlook is configured on the client computer in one of the following ways:
Uses the default Outlook security settings (that is, no Group Policy set up)
Uses security settings defined by Group Policy but does not have programmatic access policy applied
Uses security settings defined by Group Policy which is set to warn when the antivirus software is inactive or out of date
You can create a group policy to prevent security prompts from displaying if any up-to-date antivirus software is installed on the system or just turn these warning off (which is not really recommended).
Read more about that in the Security Behavior of the Outlook Object Model article.
Also you may consider using a low-level code on which Outlook is built and which doesn't give security issues - Extended MAPI. Consider using any third-party wrappers around that API such as Redemption.
Another option would be the Outlook Security Manager which allows suppressing Outlook security issues at runtime on the fly.

Accessing the ‘Body’ of an Outlook email from Excel VBA

The following Excel VBA code stopped working after upgrading from Office 2010 on Windows 7 to Office 365 on Windows 10.
Sub readbodytest()
    Dim OL As Outlook.Application
    Dim DIB As Outlook.Folder
    Dim i As Object 'Outlook.ReportItem
    Dim Filter As String
    Set OL = CreateObject("Outlook.Application")
    Set DIB = OL.Session.GetDefaultFolder(olFolderInbox)
    Const PR_SENT_REPRESENTING_EMAIL_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x0065001E"
    Filter = "#SQL=" & _
        """" & PR_SENT_REPRESENTING_EMAIL_ADDRESS & """ ci_phrasematch 'mailer-daemon' OR " & _
        """" & PR_SENT_REPRESENTING_EMAIL_ADDRESS & """ ci_phrasematch 'postmaster' OR " & _
        "urn:schemas:httpmail:subject ci_phrasematch 'undeliverable' OR " & _
        "urn:schemas:httpmail:subject ci_phrasematch 'returned'"
    For Each i In DIB.Items.Restrict(Filter)
        Debug.Print i.Body '<< Code fails here
    Next
    Set i = Nothing
    Set DIB = Nothing
    Set OL = Nothing
End Sub
In Excel, it returns
runtime error -2147467259 “Method 'Body' of object '_MailItem' failed”
The code will work when run directly in Outlook VBA, but not when run externally.
The purpose of the code is to do a bulk review of returned mail items, match information in the body of the email to a record on a database, and update the database to record the failure.
Looking to see if anyone has any suggestions before I re-write the code to run in reverse (from Outlook VBA to Excel; instead of Excel trying to retrieve from Outlook).
It makes sense to use the Logon method of the Application class which logs the user on to MAPI, obtaining a MAPI session. Here is what MSDN says:
Use the Logon method only to log on to a specific profile when Outlook is not already running. This is because only one Outlook process can run at a time, and that Outlook process uses only one profile and supports only one MAPI session. When users start Outlook a second time, that instance of Outlook runs within the same Outlook process, does not create a new process, and uses the same profile.
If Outlook is not running and you only want to start Outlook with the default profile, do not use the Logon method. A better alternative is shown in the following code example, InitializeMAPI: first, instantiate the Outlook Application object, then reference a default folder such as the Inbox. This has the side effect of initializing MAPI to use the default profile and to make the object model fully functional.
Second, I'd suggest checking the item type before accessing any properties. Not all items may contain such properties.
Another possible pitfall and most probably that is a security issue when dealing with the Outlook object model. When you try to access any sensitive property Outlook may trigger a security issue (it may be an error in the code or UI guard/prompt). "Security" in this context refers to the so-called "object model guard" that triggers security prompts and blocks access to certain features in an effort to prevent malicious programs from harvesting email addresses from Outlook data and using Outlook to propagate viruses and spam. You can use the following ways to bridge the gap:
The Security Manager for Outlook component allows to turn prompts off/on at runtime.
Use the low-level code which doesn't generate security prompts. Or any other third-party wrappers around that API (for example, Redemption).
Deploy a group policy to avoid security prompts.
Running an up-to-date antivirus software.

Excel Interlop Error on New Server after migration

I recently migrated a windows service to a new server for my company. This service reads data from a sql table and builds an excel document from it, using a template. Unfortunately, even with all of the same code, I am getting a new error when I try to execute the service.
Exception from HRESULT: 0x800A03EC
Stack Trace:
at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object
UpdateLinks, Object ReadOnly, Object Format, Object Password, Object
WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object
Delimiter, Object Editable, Object Notify, Object Converter, Object
AddToMru, Object Local, Object CorruptLoad)
This is the code which executes leading up to the error:
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Open(System.AppDomain.CurrentDomain.BaseDirectory() & strTemplatePath)
The old server is running Microsoft Windows Server 2003 SP2 and the new server is running Microsoft Windows Server 2012 Datacenter. Both have Excel 2003 installed.
What I've tried:
Prayer
Providing permissions to the user which executes the app
Setting my CurrentCulture to "en-US"
Moving the template file to c:\Templates in case of a weird issue with the program files directory
Matching the two server's settings for the "Microsoft Excel Application" within dcomcnfg and mmc-32 (neither is set to "interactive user")
Replacing the currently utilized Excel Interlop file (11.0.8161.0) with the newest version I could find (15.0.4795.1000)
Any help would be appreciated. Thanks
In response to comments:
Inspecting BaseDirectory and strTemplatePath yield a valid path to my excel workbook. If I paste it directly into the explorer address bar the file opens.
I found the answer, which turned out to be super random at the following url:
https://www.codeproject.com/Questions/574791/COMplusExceptionplushresultplus-x-a-ecplusatplu
All I had to do to get this to start working was create the following directory:
C:\Windows\SysWOW64\config\systemprofile\Desktop

How to stop OutLook Security Message programatically : A program is trying to access e-mail addresses, Allow access for 1 Minutes [duplicate]

This question already has answers here:
Suppress dialog warning that a program is trying to access my mails
(3 answers)
Closed 4 years ago.
How to stop OutLook Security Message :
A program is trying to access e-mail addresses, Allow access for 1 Minutes
I want to stop this alert programatically and want to allow vba to access inbox of outlook,, since I dont have admin access for the outlook, I cant solve this manually going to trust center settings in outlook
My code works perfectly fine but op up security msgs need to check access for 10min again and again
Using excel vba I'm accessing outlook mails and downloading attachments from mail
Dim sa, ba As Date
Dim spa As Date
Set ObjO = CreateObject("Outlook.Application")
Set olNs = ObjO.GetNamespace("MAPI")
Set objFolder = olNs.GetDefaultFolder(6)
Debug.Print objFolder
spa = Date
Dim j
j = 0
For Each item1 In objFolder.Items
sa = Format(item1.ReceivedTime, "dd-MM-yyyy")
If sa <= spa Then
If sa > spa - 30 And item1.SenderName = "PUJARY, SHRIKANTH" Then
At execution of item1.senderName line that security alert is popping up
Ran into the same thing, there is no simple solution. In essence, the popup is there to prevent the exact thing you are trying to do: Controlling Outlook remotely. It was build as a defence against VBA/Macro viruses. So no, you cannot prevent this.
Solutions are to use the Extended Messaging API (MAPI) instead, but thats no easy task. Helper libraries can be bought, for example vbMAPI or Outlook Redemption
What's the difference? While the VBA method allows you to grab into a running instance of Outlook, MAPI requires you to log into the MAPI profile using username/password. This hasn't the security problems that tapping into Outlook has and is thus safe.
If using Redemption (I am its author) is an option, modifying your script in a couple places would make it run without security prompts:
dim sItem
set sItem = CreateObject("Redemption.SafeMailItem")
For Each item1 In objFolder.Items
sItem.Item = item1
sa = Format(item1.ReceivedTime, "dd-MM-yyyy")
If sa <= spa Then
If sa > spa - 30 And sItem.SenderName = "PUJARY, SHRIKANTH" Then

Resources