VBA: MailItem.CC Doesn't Seem to be Working - vba

I've got some code designed to automatically send emails with attachments. It's been working 100% fine but I am now required to CC people as well. I thought it should be simple and added the .CC property to my MailItem but for the life of me I just can't get it to work.
I've searched the web and other questions on here but haven't been able to get anything to work.
I tried
EmailItem.Recipients.Add (CCStr)
EmailItem.Recipients.Add(CCStr).Type = olCC
but that didn't work either. The code still sends to the email listed by EmailItem.To just fine but the CC just doesn't work. I've posted my code below, any and all help is greatly appreciated.
Dim Cust_Email As String
Dim Email As Outlook.Application
Set Email = New Outlook.Application
Dim EmailItem As Outlook.MailItem
Dim CCStr As String
E1: Cust_Email = InputBox("Please enter the email of your desired recipient." & vbCrLf &
vbCrLf & "Separate mutliple emails with a semicolon: ( ; )", "Who are we sending to?", "
[Enter email here]")
If StrPtr(Cust_Email) = 0 Then
GoTo Final
ElseIf Cust_Email = vbNullString Or Cust_Email = "[Enter email here]" Then
MsgBox "You must enter an email address to forward the quote(s) to.", vbOKOnly,
"Silly goose."
GoTo E1
End If
'
CCStr = InputBox("Please enter the email for any recipients you would like cc'd on these
emails. (Leave blank if none.)", "Carbon Copy?", "")
Set EmailItem = OutApp.CreateItem(olMailItem)
EmailItem.To = Cust_Email
EmailItem.CC = CCStr
EmailItem.Subject = "Title"
EmailItem.HTMLBody = "Text"
EmailItem.Attachments.Add (filename & ".pdf")
EmailItem.Send
Final: End Sub
Thank you!

In the code you have tried to add two separate recipients to the collection:
EmailItem.Recipients.Add (CCStr)
EmailItem.Recipients.Add(CCStr).Type = olCC
Each time you call the Recipients.Add method a new recipient is added to the collection. You need to use the following approach instead:
recipientCC = recipients.Add("Eugene Astafiev")
recipientCC.Type = OlMailRecipientType.olCC;
After setting up all recipients for the item don't forget to call the Recipients.ResolveAll method which attempts to resolve all the Recipient objects in the Recipients collection against the Address Book.
You can read more about that in the How To: Fill TO,CC and BCC fields in Outlook programmatically article.

Related

Send an email with a blank subject

I am a professor interacting with students who do not respond to emails, but who do respond to text messages. So, I am writing an Outlook userform to generate text messages that are sent by Outlook to students' cell phones, e.g., by using email addresses that target the student's cell phone text message service like this: 5405551212#mms.att.net
The problem I am running into is that I don't want to have a Subject for these text messages because that Subject is added as the first line of each text sent to the student and is confusing and looks weird, but, the VBA code olMail.Send will throw this error when the Subject is blank: "Run-time error '-2147467259 (80004005)': Outlook does not recognize one or more names." The names for olMail.To and olMail.CC are fine and the error goes away when I add a non-blank Subject.
Is there a way to programmatically force Outlook to send the email with a blank subject? I have not been able to find a solution searching online other than to make the subject " " (a space)--but that is not an ideal solution because it still adds a "blank" line at the top of each text message because of the space.
I could probably use olMail.Display and then use SendKeys to send the email and answer "Yes" when I am asked if I want to send the email without a subject, but that is clunky.
How can I skip the error and send the email without a subject using VBA?
EDIT:
Here's the code that I was using to add recipients to the mailitem:
Dim olApp As Outlook.Application
Dim olMail As MailItem
olMail.To = Me.tbxEmailAddress 'this would be something like 5405551212#mms.att.net
olMail.CC = "someemail#notmail.com" 'this would be my own email address
olMail.Subject = "" 'blank subject
olMail.Body = Replace(Me.tbxTexts, vbCrLf, "") 'remove extra hard returns
olMail.Send 'this would throw the error mentioned above,
'but if I changed olMail.Subject = "" to
'olMail.Subject = "This is the subject" then no error would occur
Using #Eugene Astafiev's information below, I cobbled together a working solution like this:
Dim myRecipients As Outlook.Recipients
Dim myRecipient As Outlook.Recipient
Dim olApp As Outlook.Application
Dim olMail As MailItem
Set olApp = Outlook.Application
olMail.Subject = "" 'blank subject
olMail.Body = Replace(Me.tbxTexts, vbCrLf, "") 'remove extra hard returns
Set myRecipient = olMail.Recipients.Add(tbxEmailAddress)
myRecipient.Type = olTo 'Type is: olBCC, olCC, olOriginator, or olTo
Set myRecipient = olMail.Recipients.Add("someemail#notmail.com")
myRecipient.Type = olBCC
Set myRecipients = olMail.Recipients
If Not myRecipients.ResolveAll Then
For Each myRecipient In myRecipients
If Not myRecipient.Resolved Then
MsgBox "Could not resolve: " & myRecipient.Name
End If
Next
End If
olMail.Send 'no error now!
Interestingly, no email address using the myRecipients collection ever reported being unable to be resolved. However, when I tried to resolve the individual myRecipient object/item using myRecipient.Resolve then the text message email address (e.g., 5405551212#mms.att.net) would fail to resolve but my own email address would resolve fine.
Maybe this has something to do with 5405551212#mms.att.net not being an address in my Address Book or Contacts?
At any rate, it does send now. (Note: prior to using the myRecipients.ResolveAll, I did succeed in getting the code I originally had to work by using olMail.Display and then olMail.Send and then using SendKeys "%s" twice--the first time to "click" the Send button and the second time to "click" the "Send Anyway" button when Outlook complained there was no subject. But, clearly the VBA code approach is far superior.)
Thanks to everyone for you help!
Outlook doesn't require setting up the Subject line before submitting items. Use the Recipients.ResolveAll method which attempts to resolve all the Recipient objects in the Recipients collection against the Address Book.
Sub CheckRecipients()
Dim MyItem As Outlook.MailItem
Dim myRecipients As Outlook.Recipients
Dim myRecipient As Outlook.Recipient
Set myItem = Application.CreateItem(olMailItem)
Set myRecipients = myItem.Recipients
myRecipients.Add("Eugene Astafiev")
myRecipients.Add("Nate Sun")
myRecipients.Add("Dan Wilson")
If Not myRecipients.ResolveAll Then
For Each myRecipient In myRecipients
If Not myRecipient.Resolved Then
MsgBox myRecipient.Name
End If
Next
End If
End Sub
You may find the following articles helpful:
How To: Fill TO,CC and BCC fields in Outlook programmatically
How To: Create and send an Outlook message programmatically

How to set Outlook From email address from Word VBA

I'm trying to use Word VBA to send a document to an email recipient. For the most part, it is not difficult. I have this code so far:
With oItem
'Set the recipient for the new email
.To = "person1#mail.com"
'Set the recipient for a copy
.CC = "ccperson#mail.com"
'Set the subject
.Subject = "Blah blah"
End With
My problem is that I have several sender email addresses configured in Outlook, and Outlook is picking the wrong one by default.
Is there a way to specify a sender email address using the method above? Needless to say, the intuitive code line for specifying a sender address (.From = me#wherever.com) does not work. Thank you.
UPDATE:
I finally got my code to work after modifying it using the suggestions from peakpeak and Dimitry below. My changes were
1) to include a reference to the Microsoft Outlook 16 object library so that I could get access to the Outlook.MailItem datatype. The mail would send fine with the code above (without the reference), but would always send with the wrong From address.
2) Declare the mail item as Outlook.MailItem. This seemed to enable the SentOnBehalfOfName field.
3) Used my desired From: email address in the SentOnBehalfOfName field.
Here is the working code:
Dim MAPIMailItem As Outlook.MailItem
Set MAPIMailItem = olkApp.CreateItem(olMailItem) 'Create a new mail message
With MAPIMailItem
.BodyFormat = olFormatPlain
.to = strTo
' SentOnBehalfOfName sets the From field on my machine,
' AFTER I declared MAPIMailItem as Outlook.MailItem
.SentOnBehalfOfName = "fromAddress#foo.com"
.Subject = strSubject
.body = strBody
.attachments.Add strAtt
'.send
.Display
End With
I use this code:
Dim WantedAccount as String ' Set to preferred account name
Set MAPISession = objOutlook.Application.Session 'Get the MAPI Outlook session
Set MAPIMailItem = objOutlook.CreateItem(olMailItem) 'Create a new mail message
With MAPIMailItem
For Each Account In MAPISession.Accounts
If Account = WantedAccount Then
.SendUsingAccount = Account
Exit For
End If
Next
If you are sending through an Exchange account, set the MailItem.SentOnBehalfOfName property (assuming you have the right to send on behalf of the specified mailbox). If you are sending through a POP3/SMTP account, set the MailItem.SendUsingAccount property.

Send pre-written email from template with recipient's name in body of text

I send emails with an attachment with not much in the body of the text.
I'd like a way of entering the following:
To FirstName
Please see attached.
Kind regards,
WillacyMe
All email addresses are structured FirstName.LastName#company.com.
I need a way to add FirstName to the body of a text.
The following VBA code opens up a template:
Sub QuickAttachementTemplate()
Set temp = Application.CreateItemFromTemplate("C:\Users\WillacyMe\AppData\Roaming\Microsoft\Templates\AttachmentTemplate.oft")
temp.Display
Set temp = Nothing
End Sub
This has a space to add the FirstName and I add the email address after running the macro.
Is there a way to enter an email address in a new email and then run the macro?
Replace the FirstName placeholder with text parsed from the email address.
Option Explicit
Sub ReplacePlaceholder()
Dim tempReplacePlaceholder As MailItem
Dim recipAddress As String
Dim firstNameFromAddress As String
Dim len_firstNameFromAddress As Long
' Generate mailitem with placeholder "FirstName"
' Enter a single recipient in the To field
Set tempReplacePlaceholder = ActiveInspector.CurrentItem
tempReplacePlaceholder.Save
With tempReplacePlaceholder
recipAddress = .To
Debug.Print recipAddress
' All email addresses must be structured FirstName.LastName#company.com.
' Find first instance of "."
len_firstNameFromAddress = InStr(recipAddress, ".") - 1
Debug.Print len_firstNameFromAddress
firstNameFromAddress = Left(recipAddress, len_firstNameFromAddress)
Debug.Print firstNameFromAddress
.Body = Replace(.Body, "FirstName", firstNameFromAddress)
.Display
End With
End Sub

Can I check if a recipient has an automatic reply before I send an email?

I have a macro set up that will automatically send out emails to dozens of managers. Sometimes they're away and I have to check the away message and manually forward it to the person covering for them.
I try to find a solution before I seek help so have mercy on me! I found a similar question but it wasn't a lot of help, I couldn't find a lot of info on extracting an auto response from a recipient in a draft.
So far this is what I've got:
Sub CheckAutoReply()
Dim OL As Outlook.Application
Dim EM As Outlook.MailItem
Dim R As Outlook.Recipient
Set OL = New Outlook.Application
Set EM = CreateItem(olMailItem)
With EM
.display
.To = "John.Doe#Stackoverflow.com" 'This is a recipient I know has an autoresponse. Fictitious of course.
End With
Set R = EM.Recipients(1) 'on hover it pops up with "EM.Recipients(1) = "John.Doe#Stackoverflow.com""
Debug.Print R.Name 'this returns "John.Doe#Stackoverflow.com"
Debug.Print R.AutoResponse 'this returns nothing
Set OL = Nothing
Set EM = Nothing
End Sub
This is not a proper answer but an attempt to get you started.
Your code suggests your knowledge of Outlook VBA is limited. If this is true, I doubt that any of the approaches in “a similar question” will be appropriate. Are you familiar with Visual Studio, C++, Delphi or Redemption? Even if you managed to access PR_OOF_STATE, you would not have the alternative email address.
I would start by attempting to extract the email address from the out-of-office reply. Looking for “#” and extracting the text back to and forward to the next space might be enough.
Copy the code below to an Outlook VBA module. Select one of the out-of-office replies and run macro DemoExplorer. The objective of this macro is to show you what the text and Html bodies of the email look like. Try this macro on other replies. Are the bodies consistent? Can you see how to extract the alternative email address?
Public Sub DemoExplorer()
Dim Exp As Outlook.Explorer
Dim ItemCrnt As MailItem
Dim NumSelected As Long
Set Exp = Outlook.Application.ActiveExplorer
NumSelected = Exp.Selection.Count
If NumSelected = 0 Then
Debug.Print "No emails selected"
Else
For Each ItemCrnt In Exp.Selection
With ItemCrnt
Debug.Print "From " & .SenderName & " Subject " & .Subject
Debug.Print "Text " & Replace(Replace(Replace(.Body, vbLf, "{lf}"), vbCr, "{cr}"), vbTab, "{tb}")
Debug.Print "Html " & Replace(Replace(Replace(.HTMLBody, vbLf, "{lf}"), vbCr, "{cr}"), vbTab, "{tb}")
End With
Next
End If
End Sub
The answer to the similar question you found (Remove recipients from Outlook email if automatic reply is activated) still stands. What were you having problem with?
The only additional possibility (and this is what Outlook uses when it displays an OOF banner for a recipient you are about to send to) is to use EWS and the GetMailTips operation (see https://msdn.microsoft.com/en-us/library/office/dd877060(v=exchg.150).aspx).

How to hide BCC field in SENT email Outlook 2010 VBA

I have a macro coded to a rule that autoforwards all incoming and sent emails to a private email address in the BCC field (any auto BCC rule is disabled at the server level.) With the help of the board here, the macro works flawlessly, and for all intents and purposes is invisible.
However, if you open the SENT message in the SENT FOLDER, the BCC field is visible to all for the world to see. I have learned this is a "feature" in Outlook, apparently since 2003.
Is there a way to suppress the visibility of the BCC field when viewing the SENT email?
Or is there a way one can set the display options of an individual folder NOT to display a BCC - EVER?
Thank you for any assistance.
My code:
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim objRecip As Recipient
Dim strMsg As String
Dim res As Integer
Dim strBcc As String
Dim answer
Dim oAtt
Dim strProc1 As String
On Error GoTo Application_ItemSend_Error
strBcc = "myprivateemail#gmail.com"
Set objRecip = Item.Recipients.Add(strBcc)
objRecip.Type = olBCC
If Not objRecip.Resolve Then
strMsg = "Could not resolve the Bcc recipient. " & _
"Do you want still to send the message?"
res = MsgBox(strMsg, vbYesNo + vbDefaultButton1, _
"Could Not Resolve Bcc Recipient")
If res = vbNo Then
Cancel = True
End If
End If
Set objRecip = Nothing
On Error GoTo 0
Exit Sub
Application_ItemSend_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") " & "Error on
Line " & Erl & " in procedure Application_ItemSend of VBA Document
ThisOutlookSession"
End Sub
If you want to remove BCC recipients in the Sent Items folder, listen for the Items.ItemAdd event on the Sent Items folder, loop through all recipients in the MailItem.Recipients collection and delete recipients with Recipient.Type = olBCC.
"the BCC field is visible to all for the world to see"
Well, if anyone in the world can view your own sent folder, then this is the case. Otherwise the BCC field is not part of the email, recipients do not receive it. The goal of the feature is to have the ability to recall your own BCC messages, so you do not forget that you have sent them.
Try the following...
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim olRec As Outlook.Recipient
Dim Address$
Address = "Om3r#blala.com"
Set olRec = Item.Recipients.Add(Address)
olRec.Type = olBCC
olRec.Resolve
End Sub