I am trying to auto email a report from access using VBA in a macro. The report is sent from Access2007 by outlook2007. When the report is being sent, I get a security message from outlook saying "a program is trying to access your Address book or Contacts" or "a program is trying to access e-mail addresses you have stored in Outlook..." . This message is a problematic for me because I want to use windows task scheduler to automatically send the report without any human interaction.So I want to disable this security notification. I searched on Google and here is the code I have so far but giving me errors and I am not sure what else I should do. Thanks for your help in advance. I am a beginner programmer. The error is
Public Sub Send_Report()
Dim strRecipient As String
Dim strSubject As String
Dim strMessageBody As String
Dim outlookapp As Outlook.Application
Set outlookapp = CreateObject("Outlook.Application")
OlSecurityManager.ConnectTo outlookapp 'error is here says object required
OlSecurityManager.DisableOOMWarnings = True
On Error GoTo Finally
strRecipient = "example#yahoo.com"
strSubject = "Tile of report"
strMessageBody = "Here is the message."
DoCmd.SendObject acSendReport, "Report_Name", acFormatPDF, strRecipient, , , strSubject, strMessageBody, False
Finally:
OlSecurityManager.DisableOOMWarnings = False
End Sub
You get the error because OlSecurityManager is nothing. You haven't declared it, you haven't set it to anything, so when you attempt to use it, VBA has no idea what you're talking about!
It looks like you're trying to use Outlook Security Manager, which is an add-in sold here. Have you purchased it? Because if not, then you probably don't have it on your system.
If you do have it, then you probably need to declare and set it like this:
Dim OlSecurityManager As AddinExpress.Outlook.SecurityManager
Set OlSecurityManager = New AddinExpress.Outlook.SecurityManager
If you, as I suspect, don't have it, then an alternative is sending e-mail using CDO. Here's an example:
First, set a reference to the CDO library in Tools > References > checkmark next to Microsoft CDO for Windows Library or something like that.
Dim cdoConfig
Dim msgOne
Set cdoConfig = CreateObject("CDO.Configuration")
With cdoConfig.Fields
.Item(cdoSendUsingMethod) = cdoSendUsingPort
.Item(cdoSMTPServerPort) = 25 'your port number, usually is 25
.Item(cdoSMTPServer) = "yourSMTPserver.com"
'.Item(cdoSendUserName) = "your username if required"
'.Item(cdoSendPassword) = "your password if required"
.Update
End With
Set msgOne = CreateObject("CDO.Message")
With msgOne
Set .Configuration = cdoConfig
.To = "recipient#somehwere.com"
.from = "you#here.com"
.subject = "Testing CDO"
.TextBody = "It works just fine."
.Attachments.Add "C:\myfile.pdf"
.Send
End With
This is a bit more annoying than Outlook, because you need to know in advance the address of the SMTP server to be used.
I know this is a late answer, but I just ran into a similar problem. There is another solution using Outlook.Application!
I stumble upon it while looking for the solution, full credit here:
http://www.tek-tips.com/faqs.cfm?fid=4334
But what this site's solution simply suggest, instead of using the .send command, use the `.Display" command and then send some keys from the keyboard to send the email, like below:
Sub Mail_workbook_Outlook()
'Working in Excel 2000-2016
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = "Someone#Somewhere.com"
.CC = ""
.BCC = ""
.Subject = "This is an automated email!"
.Body = "Howdy there! Here, have an automated mail!"
.Attachments.Add ActiveWorkbook.FullName
.Display 'Display instead of .send
SendKeys "%{s}", True 'send the email without prompts
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End
End Sub
Related
I have an access macro that runs a set of Netezza queries and uploads the results to a database. It then opens and refreshes an Excel file that utilizes this data and saves the file in a couple of locations. Finally it composes an automated email and sends it to a distribution list. When I manually run the macro, everything works 100% perfectly.
In order to make my life a bit easier, I am using Windows Task Scheduler (Windows 10) to automatically fire the macro once a day, and this is where my issue lies. Task Scheduler fires the macro off without a hitch, all of the queries refresh, the excel files are saved, but the e-mail is not sent.
Here is the code SendOutlookEmail code that I'm using
Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Dim SpDate As String
Dim Signature As String
Dim StrPath As String
Dim StrFilter As String
Dim StrFile As String
SpDate = Format(Now() - 1, "yyyy-mm-dd")
Set oApp = CreateObject("Outlook.application")
Set oMail = oApp.CreateItem(olMailItem)
With oMail
.Display
End With
Signature = oMail.HTMLBody
With oMail
.SentOnBehalfOfName = "My Email"
.To = "CCO Reporting"
.Subject = "AHT - ACW Dashboard - " & SpDate
.HTMLBody = "<span LANG=EN>" _
& "<font FACE=SegoeUI SIZE = 3>" _
& "The IB/OB AHT - ACW reports have been updated and placed in the following folder:" _
& "<br><br>" _
& "<a href='File Location'>File Location</a>" & "<br><br><br></font></span>" _
& Signature
'.Attachments.Add (StrPath & StrFile)
'.Display
.Send
End With
On Error GoTo 0
Set oMail = Nothing
Set oApp = Nothing
End Sub
Here is the task scheduler settings
Task Scheduler
Possibly Outlook just doesn't have enough time to send the message, as it instantly gets closed after the message is moved to the outbox (.send doesn't send the message as far as I know, but just moves it to the outbox and triggers a send for all items in there).
Try to manually add a send/receive, to make Access wait for Outlook to actually send the mails (add this to your vba before the Set oApp = Nothing):
' Synchronizes (ie sends/receives) OL folders.
' Ref: http://msdn.microsoft.com/en-us/library/ff863925.aspx
Dim objNsp As Outlook.NameSpace
Dim colSyc As Outlook.SyncObjects
Dim objSyc As Outlook.SyncObject
Dim i As Integer
On Error GoTo SyncOL_Err
Set objNsp = oApp.Application.GetNamespace("MAPI")
Set colSyc = objNsp.SyncObjects
For i = 1 To colSyc.Count
Set objSyc = colSyc.Item(i)
Debug.Print objSyc.Name
objSyc.start
Next
Set objNsp = Nothing: Set colSyc = Nothing: Set objSyc = Nothing
I'm building a scheduling database for my office, and have it mostly finished. The last step is sending an automated meeting out for the schedule created each day. This email MUST come from a secondary email account/calendar shared by all members of my team. The code below runs just fine on my personal computer, but will not run on others even though they have access to the same email and calendar.
The error I get is this:
run-time error '-2147221233(8004010f)': The attempted operation failed. An object could not be found.
The line it's screwing up on is this: Set OLFolder = OLNamespace.Folders.Item("name#address.office.com")
Here's my code:
Private Sub sendacdcsched_Click()
'sends an email with a calendar appointment for the facility schedule.
DoCmd.Save 'saves the record first
Dim OutlookApp As Object
Dim Outlookmessage As Object
Dim scheduleACDC As String
Dim OLNamespace As Object
Dim OLFolder As Object
scheduleACDC = "Schedule for ACDC for " & Me.schedDate.Value
'Create Instance of Outlook
On Error Resume Next
Set OutlookApp = GetObject(Class:="Outlook.Application") 'Handles if Outlook is already open
Err.Clear
If OutlookApp Is Nothing Then Set OutlookApp = CreateObject(Class:="Outlook.Application") 'If not, open Outlook
On Error GoTo 0
Set OLNamespace = OutlookApp.getnamespace("MAPI")
Set OLFolder = OLNamespace.Folders.Item("name#address.office.com")
'Create a new email message
Set Outlookmessage = OLFolder.items.Add(1)
'Create Outlook email with attachment
On Error Resume Next
With Outlookmessage
.meetingstatus = 1 'makes it a meeting so you can add recipients
.start = Me.schedDate & " 8:00:00 AM"
.duration = 240 'in minutes
.To = "" 'Insert all emails addresses to be sent to here'
.subject = "ACDC" 'email subject line'
.Body = scheduleACDC
.Display 'displays email before you send it. If you wish to send without seeing it displayed use .send'
End With
On Error GoTo 0
End Sub
I am in MS Access 2013 trying to set the Reply To address for a olMailItem with Outlook 2013.
My current code is giving me:
Run-time error '287'
Application-defined or object-defined error
Private Sub email_button_click()
' *** SETUP OUTLOOK ***
Dim OutApp As Outlook.Application
Dim OutMail As Outlook.MailItem
Set OutApp = New Outlook.Application
Set OutMail = OutApp.CreateItem(olMailItem)
' *** DO SOME OTHER STUFF ****
....
With OutMail
.Subject = "Test"
.Body = "Whatever"
.To = "test#test.com"
.ReplyRecipients.Add "notatest#test.com" <- Error here
.Display
End With
' *** TIDY UP ***
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Plenty of others seem to be able to do it. ie :
Change reply address in Outlook mail
http://www.ozgrid.com/forum/showthread.php?t=186882
http://www.vbaexpress.com/forum/archive/index.php/t-19993.html
Thanks
Doug
I have absolutely no problem running the following script in Outlook VBA or OutlookSpy (I am its author) script editor.
Set OutMail = Application.CreateItem(olMailItem)
With OutMail
.Subject = "Test"
.Body = "Whatever"
.To = "test#test.com"
.ReplyRecipients.Add "notatest#test.com"
.Display
End With
If Outlook is not running, make sure you call Namespace.Logon fist:
set ns = Application.GetNamespace("MAPI")
ns.Logon
I have seen this on a Enterprise system where the group policy was blocking VBA scripts on Outlook 2013.
The solution is to turn the GP off.
Just list it a second time, you are "adding" recipiants
.ReplyRecipients.Add "notatest1#test.com"
.ReplyRecipients.Add "notatest2#test.com"
How can I get current Office Windows account email using VBA code?
I do not mean the account which the user is logged in the Windows, I mean the account that is authorized in office
See image:
I don't believe you can access it. Your best bet is linking Access to Outlook and trying to access it from there.
For example you Set a reference to the Outlook object library and then :-
Dim olook As Outlook.Application
Dim EAddress As String
Set olook = GetObject(, "Outlook.Application")
Set olook = CreateObject("Outlook.Application")
EAddress = olook.Session.CurrentUser.Address
I have a similar solution calling out to Outlook, I'm using Excel and found a way to do this, I've only ever found one address in the Accounts collection, but have a suffix match to try and catch the #company.com I'm looking for:
Dim NameSpace As Object
Dim strEmailAddress As String
Set NameSpace = CreateObject("Outlook.Application").GetNameSpace("MAPI")
strEmailAddress = ""
For Each Account In NameSpace.Accounts
If LCase(Split(Account.SMtpAddress, "#")(1)) = "contoso.com" Then
strEmailAddress = Account.SMtpAddress
Else
strEmailAddress = "Unknown"
End If
' If you want to see more values, uncomment these lines
'Debug.Print Account.DisplayName
'Debug.Print Account.UserName
'Debug.Print Account.SMtpAddress
'Debug.Print Account.AccountType
'Debug.Print Account.CurrentUser
Next
Outlook interrupts the VBA-execution (to access Outlook objects from macro) due to security.
Snap shot
Outlook Security
Hence only to get eMailID without opening object as well as handling error in case of non availability of outlook/account, following code can work in your case
VBA Code
Sub Email_Address()
Dim MAPI As Object
Status = "unknown"
On Error GoTo return_value
Set MAPI = CreateObject("Outlook.Application").GetNameSpace("MAPI")
i = 1
Do While True
Debug.Print MAPI.Accounts.Item(i)
i = i + 1
Loop
return_value:
If i > 1 Then: Status = "done..."
Debug.Print Status
End Sub
This is in Access 2010 and I have virtually no experience or familiarity with VBA.
In my form (frmEmailLookup), I have combo boxes and list boxes and a subform set up so that when the user selects a building from cmbBuilding the remainder of the form populates with the data on that building, including the contact emails for up to 4 people in the building (lstBuildingRepEmail1, lstBuildingRepEmail2, lstBuildingRepEmail3, lstBuildingRepEmail4). I need a button (butEmailRecords) to generate an email with the query from the subform (qryBuildingAreaLookup) as an attachment. I can set up a macro that will something close, but it doesn't allow for dynamic email addresses. I don't want my users to have to go that far into the program to make updates.
Any help is appreciated and I know I'm asking for a lot of code writing help.
Here's what I've tried:
Option Compare Database
Private Sub butEmailRecords_Click()
Dim outputFileName As String
outputFileName = CurrentProject.Path & "\BuildingInventory" & ".xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "qryBuildingAreaLookup", outputFileName, True
On Error GoTo Error_Handler
Dim objOutlook As Outlook.Application
Dim objEmail As Outlook.MailItem
Set objOutlook = CreateObject("Outlook.application")
Set objEmail = objOutlook.CreateItem(olMailItem)
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("qryBuildinAreaLookup")
With rs
With objEmail
.To = tblBuilding.BuildingRep1
.To = tblBuilding.BuildingRep2
.To = tblBuilding.BuildingRep3
.To = tblBuilding.BuildingRep4
.Subject = "Look at this sample attachment"
.body = "The body doesn't matter, just the attachment"
.Attachments.Add "L:\Administration\FacilityInventoryDatabase\BuildingInventory.xls x"
.Send
'.ReadReceiptRequested
End With
Exit_Here:
Set objOutlook = Nothing
Exit Sub
Error_Handler:
MsgBox Err & ": " & Err.Description
Resume Exit_Here
End Sub
Here is the basics of what I use:
'Refers to Outlook's Application object
Dim appOutlook As Object
'Refers to an Outlook email message
Dim appOutlookMsg As Object
'Refers to an Outlook email recipient
Dim appOutlookRec As Object
'Create an Outlook session in the background
Set appOutlook = CreateObject("Outlook.Application")
'Create a new empty email message
Set appOutlookMsg = appOutlook.CreateItem(olMailItem)
'Using the new, empty message...
With appOutlookMsg
'SQL statement to grab emails
Set recordset = currentdb.openrecordset('SQL statement')
Do While Not recorset.EOF
Set appOutlookRec = .Recipients.Add(recordset.Email)
appOutlookRec.Type = olTo
recordset.MoveNext
Loop
.Subject = ....
.Body = ....
.Send
End With
and that's the basics of what I use. I'm a beginner so this may not be the best way, but it should be a start. (I also had to add Microsoft Oulook in the reference library.)
I use CDO objects to send messages because I prefer not to rely on Outlook (for anything).
There is quite a comprehensive article on using CDO to send mail (including downloadable VBA code) here:
http://www.cpearson.com/excel/Email.aspx