System administrator unable to send olBCC mail - vba

I have a custom outlook appointment, from which I want to automatically BCC a mail upon sending my a appointment invitation.
Function Item_Send()
Set oMsg = Application.ActiveInspector.CurrentItem
With oMsg
Set objRecip = Item.Recipients.Add("MyEmail#mail.com")
objRecip.Type = olBCC
objRecip.Resolve
End With
Set oMsg = Nothing
End Function
Everything seems to work fine - My email is attached as BCC, and the appointment is successfully being send.
However, in my inbox I'm getting a mail, that the BCC mail could not be reached.
Your message did not reach some or all of the intended recipients.
Subject:
Sent: 18/06/2020 14:49
The following recipient(s) cannot be reached:
MyEmail on 18/06/2020 14:49
'MyEmail#mail.com' on 18/06/2020 14:49
This message could not be sent. Try sending the message again later, or contact your network administrator.
Diagnostic information for administrators:
Error is [0x80070057-0x00000000-0x00000000]. Submit-Message failed:
message id(23), failure enum(7), HResult(0x80070057), EC(-2147024809).
Why is this error occuring? My mail is not incorrect.

It is not clear where the Item object comes from.
First of all, the Type property for MeetingItem recipients can be one of the following OlMeetingRecipientType constants: olOptional, olOrganizer, olRequired, or olResource. If you want to send a BCC I'd recommend creating a new mail item and copy properties to the new item.
Anyway, the Resolve method returns a boolean value which is true if the object was resolved; otherwise, false. For example, that is how you need to check this out:
Sub AssignTask()
Dim myItem As Outlook.TaskItem
Dim myDelegate As Outlook.Recipient
Set MyItem = Application.CreateItem(olTaskItem)
MyItem.Assign
Set myDelegate = MyItem.Recipients.Add("Eugene Astafiev")
myDelegate.Resolve
If myDelegate.Resolved Then
myItem.Subject = "Prepare Agenda For Meeting"
myItem.DueDate = Now + 30
myItem.Display
myItem.Send
End If
End Sub
Be aware, the ItemSend event handler accepts two parameters. For example, the following code in VB.NET works like a charm on my machine:
Imports System.Runtime.InteropServices
' ...
Private Sub OnItemSend(Item As System.Object, ByRef Cancel As Boolean) _
Handles Application.ItemSend
Dim recipient As Outlook.Recipient = Nothing
Dim recipients As Outlook.Recipients = Nothing
Dim mail As Outlook.MailItem = TryCast(Item, Outlook.MailItem)
If Not IsNothing(mail) Then
Dim addToSubject As String = " !IMPORTANT"
Dim addToBody As String = "Sent from my Outlook 2010"
If Not mail.Subject.Contains(addToSubject) Then
mail.Subject += addToSubject
End If
If Not mail.Body.EndsWith(addToBody) Then
mail.Body += addToBody
End If
recipients = mail.Recipients
recipient = recipients.Add("Eugene Astafiev")
recipient.Type = Outlook.OlMailRecipientType.olBCC
recipient.Resolve()
If Not IsNothing(recipient) Then Marshal.ReleaseComObject(recipient)
If Not IsNothing(recipients) Then Marshal.ReleaseComObject(recipients)
End If
End Sub
This event triggers right after the user clicks the Send button in Outlook (before the inspector window is closed) or when the Send method of Outlook items is called. The ItemSend event provides two parameters to the programmer:
The Item object – an Outlook item that is going to be sent. It can be represented by the AppointmentItem, MailItem, MeetingItem, MobileItem, SharingItem, TaskItem classes.
The Cancel parameter – allows you to cancel sending in Outlook. The default value is false. If you set the Cancel parameter to true in the event handler, the sending process is canceled and the inspector window is shown to the user.
Read more about that in the How To: Change an Outlook e-mail message before sending using C# or VB.NET article.

Related

How to load combobox value to CC field in Outlook VBA?

I have a userform combobox that allows users to select a project email. I want to be able to select this email, and click on a button in the userform which loads the email into the CC field. I've got this code right now, but it's giving me an error. Any help is appreciated.
Private Sub Attach_Click()
Set oMsg = Application.ActiveInspector.CurrentItem
Dim objRecip As Recipient
Set objRecip = oMsg.Recipients.Add(Me.cmbPC.column(0))
objRecip.Type = olCC
End Sub
Error that pops up:
The operation failed. The messaging interfaces have returned an unknown error. If the problem persists, restart Outlook. Cannot resolve recipient.
Use the Recipient.Resolve method which attempts to resolve a Recipient object against the Address Book.
Sub CreateAssignedTask()
Dim myItem As Outlook.TaskItem
Dim myDelegate As Outlook.Recipient
Set MyItem = Application.CreateItem(olTaskItem)
MyItem.Assign
Set myDelegate = MyItem.Recipients.Add("Eugene Astafiev")
myDelegate.Resolve
If myDelegate.Resolved Then
myItem.Subject = "Test task"
myItem.Display
End If
End Sub
You may find the How To: Fill TO,CC and BCC fields in Outlook programmatically article helpful.

Send an email and ReplyAll to it

My task is to send an email containing a report and send another email containing another report to the same email thread by way of replying/forwarding to the sent email (excluding some recipients).
Option Explicit
Sub TestReply()
Dim objApp As Application
Dim objNewMail As Outlook.MailItem
Dim objReply As Outlook.MailItem
Set objApp = Outlook.Application
Set objNewMail = objApp.CreateItem(0)
' Outgoing email
With objNewMail
.Subject = "Test sending email"
.To = "abc#abc.com"
.HTMLBody = "This is the outgoing email."
.Send
End With
' Reply email
Set objReply = objNewMail.ReplyAll
With objReply
.HTMLBody = "This is the reply emal."
.Display
End With
Set objApp = Nothing
Set objNewMail = Nothing
Set objReply = Nothing
End Sub
I can't find a way to send the follow up email (either by reply or forward).
When I try the above code, it says error the item is moved/deleted. I guess it is becaused when the email is sent, the objNewMail odject is also terminated.
I tried adding RE: or FW: to the subject of the original email but then the two emails will not be in the same thread but independent emails.
An additional problem is that I have two email accounts in Outlook: my own email and team email and the reports are to be sent from the team email.
You can determine if an item added to the sent folder matches objNewMail.
In ThisOutlookSession
Option Explicit
Private WithEvents sentFolderItems As Items
Private Sub Application_Startup()
'Set sentFolderItems = Session.GetDefaultFolder(olFolderSentMail).Items
' Reference any folder by walking the folder tree
' assuming the team folder is in the navigation pane
Set sentFolderItems = Session.folders("team mailbox name").folders("Sent").Items
End Sub
Private Sub sentFolderItems_ItemAdd(ByVal Item As Object)
Dim myReplyAll As MailItem
If Item.Class = olMail Then
'do not use InStr unless you change some part of words in original subject
' or another reply will be generated
If Item.Subject = "Test sending email" Then
Set myReplyAll = Item.ReplyAll
With myReplyAll
.HTMLBody = "This is the reply email."
.Display
End With
End If
End If
End Sub
Sub TestReply()
Dim objNewMail As MailItem
'Set objNewMail = CreateItem(olMailItem)
' Add, not create, in non-default folder
Set objNewMail = Session.folders("team mailbox name").folders("Inbox").Items.Add
' Outgoing email
With objNewMail
.Subject = "Test sending email"
.To = "abc#abc.com"
.HTMLBody = "This is the outgoing email."
.Send
End With
End Sub
Note: Application. and Outlook. are not needed when code is in Outlook.
Call Send on the original email (objNewMail) only after you construct the reply.
Right so currently your code is doing this:
Creating a mail, sending it.
Trying to reply to the mailitem object which is already sent.
What you need is an event Hook to catch the mail when it's received by yourself. (assuming this is how you're reply all and removing some recipients for report 2)
Here is how you accomplish this:
First Create a WithEvents as Items call AllMyItems, then a hook in the AllMyItems_ItemAdd, then initialize the event when Outlook Starts using Application_Startup (a built in event)
Be very careful to identify criteria for forwarding / actioning the incoming mail item, since this event code will scan every mail sent to your main inbox and evaluate it. IF you want to further reduce the risk of forwarding a mail item to the wrong person, consider using an outlook rule to sort it into a custom folder, and then setting that folder's location as the Set AllMyItems = line instead of default folder
Option Explicit
'for the Default DL inbox
Private WithEvents AllMyItems As Items
Private Sub Application_Startup()
Dim olapp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olapp = Outlook.Application
Set objNS = olapp.GetNamespace("MAPI")
'Set myolitems = objNS.GetDefaultFolder(olFolderInbox).Items
'all my items in the main box
Set AllMyItems = objNS.GetDefaultFolder(olFolderInbox).Items
Set olapp = Nothing
Set objNS = Nothing
End Sub
Private Sub AllMyItems_ItemAdd(ByVal Item As Object)
On Error Resume Next
If TypeName(Item) <> "Mailitem" Then
If TypeName(Item) = "ReportItem" Then GoTo 0 'undeliverables shows as a report item
If TypeName(Item) = "MeetingItem" Then GoTo 0
Dim oItem As MailItem
Dim myForward As MailItem
Set oItem = Item
'use the next line to check for a property of the incoming mail, that distinguishes it from other mail, since this event will run on every mail item
If InStr(1, oItem.Subject, "Your public folder is almost full", vbTextCompare) > 0 Then
Set myForward = oItem.Forward
myForward.Recipients.Add "derp#derpinacorp.com"
myForward.Importance = olImportanceHigh
'MsgBox "uno momento"
myForward.Send
Else
End If
Else
End If
0:
End Sub

objItems_ItemAdd not triggered when items added to olItems: How to apply the ItemAdd event?

I want to set an auto-category for the incoming email in Outlook 2010 but my code does not work.
I restarted Outlook many times.
Public WithEvents olItems As Outlook.Items
Private Sub Application_Startup()
Set objItems = Outlook.Application.Session.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub objItems_ItemAdd(ByVal Item As Object)
Dim objMail As Outlook.MailItem
Dim strSenderEmailAddress As String
Dim objContacts As Outlook.Items
Dim objContact As Object
Dim objFoundContact As Outlook.ContactItem
Dim strFilter As String
Dim strContactCategory As String
Dim i As Long
If TypeOf Item Is MailItem Then
Set objMail = Item
strSenderEmailAddress = objMail.SenderEmailAddress
Set objContacts =
Outlook.Application.Session.GetDefaultFolder(olFolderContacts).Items
For Each objContact In objContacts
If TypeOf objContact Is ContactItem Then
For i = 1 To 3
strFilter = "[Email" & i & "Address] = " &
strSenderEmailAddress
Set objFoundContact = objContacts.Find(strFilter)
'Check if the sender exists in your contacts folder
If Not (objFoundContact Is Nothing) Then
strContactCategory = objFoundContact.Categories
'If the corresponding contact has no category
'Assign the "Known" category to the email
If strContactCategory = "" Then
objMail.Categories = "Known"
'If the contact has, directly use its category
Else
objMail.Categories = strContactCategory
End If
Exit For
End If
Next i
'If the sender doesn't exist in the Contacts folder
'Assign the "Unknown" category to the email
If objFoundContact Is Nothing Then
objMail.Categories = "Unknown"
End If
End If
Next objContact
End If
End Sub
I am not good in VBA. When new email arrives my mailbox, it is not auto-categorized, no color filling in Category field in Outlook, nothing happens.
I want to set auto-category for the incoming email in outlook 2010 but my code does not work.
First of all, you need to handle the NewMailEx event of the Application class which is fired when a new item is received in the Inbox.
The NewMailEx event fires when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID returned in the EntryIDCollection array to call the NameSpace.GetItemFromID method and process the item. Use this method with caution to minimize the impact on Outlook performance. However, depending on the setup on the client computer, after a new message arrives in the Inbox, processes like spam filtering and client rules that move the new message from the Inbox to another folder can occur asynchronously.
After getting the item received you may set a category.
P.S. The ItemAdd event may not be fired at all if you receive more than sixteen items simultaneously. This is a known issue in the Outlook object model.

How to create autoreply with number of unread mails in inbox using Outlook VBA?

I am trying to trigger a script with rules to send an autoreply.
"Hi thanks for your mail, your mail has been placed in a queue there are XX number of e-mails in front of you, we will answer as soon as possible."
The XX should be the number of unread e-mails.
I found outlook automated reply with unread message count:
Private Sub myOlItems_ItemAdd(ByVal Item As Object)
End Sub
Sub AutoResponse(objmsg As Outlook.MailItem)
' define my reply message
Dim objReply As MailItem
' let's get ourselves the inbox!
Dim inbox As MAPIFolder
Set inbox = Application.GetNamespace("MAPI"). _
GetDefaultFolder(olFolderInbox)
' Let's get this reply going!
Set objReply = objmsg.Reply
' Subject Re: their subject. Standard
objReply.Subject = "Re: " & objReply.Subject
' Body - you define this, use the variable for the unread count in inbox
objReply.Body = "Your email has been received. I currently have " & inbox.UnReadItemCount & " unread emails in my inbox and I will get yours as soon as I can"
' Send this thing!
objReply.Send
' Reset
Set objReply = Nothing
End Sub
It doesn't work.
I am on Outlook 2016, with an exchange mail server.
Your Items.ItemAdd Event is not set correctly, Try the flowing code without Outlook rule, Make sure to restart your Outlook
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olNs As Outlook.NameSpace
Dim Inbox As Outlook.MAPIFolder
Set olNs = Application.GetNamespace("MAPI")
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
Set Items = Inbox.Items
End Sub
Private Sub Items_ItemAdd(ByVal Item As Object)
If TypeOf Item Is Outlook.mailitem Then
AutoResponse Items
End If
End Sub
Private Sub AutoResponse(Item As Outlook.mailitem)
Dim Reply As Outlook.mailitem ' Reply msg
Dim Inbox As Outlook.MAPIFolder ' Inbox
Set Inbox = Application.GetNamespace("MAPI") _
.GetDefaultFolder(olFolderInbox)
' Let's get this reply going!
Set Reply = Item.Reply
' Subject Re: their subject. Standard
Reply.subject = Reply.subject
' Body - you define this, use the variable for the unread count in inbox
Reply.HTMLBody = "Your email has been received. I currently have " & _
Inbox.UnReadItemCount & _
" unread emails in my inbox and I will get yours as soon as I can"
' Send this thing!
Reply.Send
' Reset
Set Reply = Nothing
End Sub
You need to create a rule in Outlook manually and assign the VBA macro sub (AutoResponse) to the rule. Only then you will get the code running.
As a possible workaround you can handle the NewMailEx event of the Application which is fired when a new item is received in the Inbox. The event fires when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID returned in the EntryIDCollection array to call the NameSpace.GetItemFromID method and process the item. See Outlook's Rules and Alerts: Run a Script for more information.
For users with an Exchange Server account (non-Cached Exchange Mode or Cached Exchange Mode), the event will fire only for messages that arrive at the server after Outlook has started. The event will not fire for messages that are synchronized in Cached Exchange Mode immediately after Outlook starts, nor for messages that are already on the server when Outlook starts in non-Cached Exchange Mode.

Outlook attachments send then move

how do I move the files once its been send out successfully to c:\complete
Can I limit the attachments to 10 attachments per email.
each file size is like 300kb
Option Explicit
Sub SendMessage(Optional AttachmentPath)
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Dim objOutlookFile As String
'// Attachment Path
AttachmentPath = "C:\Reports\"
'// Create the Outlook session.
Set objOutlook = CreateObject("Outlook.Application")
'// Create the message.
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
With objOutlookMsg
'// Add the To recipient(s) to the message.
Set objOutlookRecip = .Recipients.Add("omar")
Set objOutlookRecip = .Recipients.Add("omar")
objOutlookRecip.Type = olTo
'// Add the CC recipient(s) to the message.
Set objOutlookRecip = .Recipients.Add("omar")
objOutlookRecip.Type = olCC
'// Set the Subject, Body, and Importance of the message.
.Subject = "Reports"
.Body = "the Attached reports are complete !" & vbCrLf & vbCrLf
.Importance = olImportanceHigh '//High importance
'// Add attachments to the message.
objOutlookFile = Dir(AttachmentPath & "*.*")
Do While Len(objOutlookFile) > 0
.Attachments.Add AttachmentPath & objOutlookFile
objOutlookFile = Dir
Loop
'// Resolve each Recipient's name.
For Each objOutlookRecip In .Recipients
objOutlookRecip.Resolve
If Not objOutlookRecip.Resolve Then
objOutlookMsg.Display
End If
Next
'//.DeleteAfterSubmit = True
'//.Send
.Display
End With
Set objOutlookMsg = Nothing
Set objOutlook = Nothing
End Sub
It is not clear where you run the VBA macro code (Outlook, Word, Excel and etc.).
Anyway, there is no need to create a new Outlook Application instance in the Outlook VBA macro:
'// Create the Outlook session.
Set objOutlook = CreateObject("Outlook.Application")
Instead, you can use the Application property, for example:
'// Create the message.
Set objOutlookMsg = Application.CreateItem(olMailItem)
You can use the FileSystemObject for managing files on the disk. See Accessing Files with FileSystemObject for more information.
Also the Outlook object model provides the BeforeAttachmentAdd event for Outlook items which is fired before an attachment is added to an instance of the parent object. It provides an instance of the Attachment class to be added and the Cancel parameter which can be used to cancel the action. Just set to true to cancel the operation; otherwise, set to false to allow the Attachment to be added.
sorry one more question, can I stop outgoing email if there is no files in c:\reports\
The best way is to check the folder before runnig the VBA macro. You can use the FileSystemObject to get the job done.
The Application class from the Outlook object model provides the ItemSend event which is fired whenever an Microsoft Outlook item is sent, either by the user through an Inspector (before the inspector is closed, but after the user clicks the Send button) or when the Send method for an Outlook item, such as MailItem, is used in a program. It provides the item reference being sent and the Cancel parameter. If the event procedure sets the Cancel argument to true, the send action is not completed and the inspector is left open.
You can use both these events to check out whatever you need.
Finally, you may find the Getting Started with VBA in Outlook 2010 article in MSDN helpful.