Sending Massive emails on excel vba, OLE issue - excel

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.

Related

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.

How to set alias as the From account?

I have VBA code in Excel that sends an email via Outlook 365.
My primary email account (#outlook.com) has five aliases. These are not separate email accounts but merely aliases associated with that primary account (which itself is one out of a half a dozen primary accounts). []
I'd like to set one of those aliases as the From address.
This is the relevant snippet; everything else in the Sub, including creating the email and setting the attributes and attachments, works.
Dim emailAlias As String
emailAlias = "f...#outlook.com"
Set Mail_Object = CreateObject("Outlook.Application")
Set Mail_Single = Mail_Object.CreateItem(0)
With Mail_Single
.Subject = Subject
.To = Cells(cellRow, 2).Value
.SentOnBehalfOfName = emailAlias 'doesn't work
.SendUsingAccount = emailAlias 'no go either
.HTMLBody = msg
.Attachments.Add fileName
.Display
End With
Setting the alias as the default account can only be done online at live.com. It would be too cumbersome to (re)set it several times a day, plus it takes Outlook 365 forever to recognize the switch.
Is there a way to specify an alias of a primary account as the From email address?
Outlook (at least in its current version) would not let you send using one of the proxy SMTP addresses - the message is always sent using the default SMTP address of the account.
You can do that only if you either configure a dummy POP3/SMTP account or use a utility like Proxy Manager (I am its author) - see https://www.msoutlook.info/question/send-mail-from-additional-exchange-address-or-alias for more details.

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

Accessing outlook message body with excel vba: error 287

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

Creating and mailing Excel spreadsheets in Windows Phone 8 apps

I am doing WP, which is contain List of data, and I am trying to add those data into excel sheet.
And this sheet will be attach my mail when I send the mail..
I got one dll but this is still give me error when I generate excel sheet and I press Ok then it will work but I am not satisfied with this is there any other option where I can achieve this scenario..
First and foremost - what DLL are you using? What kind of error are you getting?
Second, if you want to send the document in an email (as an attachment), you won't be able to do that with the out-of-the-box EmailComposeTask. Instead, you could use the LiveMailMessage library:
MailMessage mailMessage = new MailMessage();
mailMessage.Email = "test#email.id";
mailMessage.Password = "somePassword";
mailMessage.AccountType = MailMessage.accountType.MicrosoftAccount;
mailMessage.To = "destination#email.id";
mailMessage.Subject = "Test Subject";
mailMessage.Body = "Test Body";
mailMessage.AddAttachement("/Path/to/Spreadsheet");
mailMessage.Send();

Resources