Send existing email as attachment using vba

  • Thread starter Thread starter Crossh
  • Start date Start date
C

Crossh

Using VBA, is there a way to send an existing email from my Inbox, as an
attachment to a new email which was created in code? I have already written
the code to find the email I want to attach. I just can't figure out how to
attach it. Thanks for your help.
 
Thanks for the quick response! I get the MailItem.Attachments.Add part.
I'm stuck on the "SomeOtherMailItem" part.
Using the following code, what would "SomeOtherMailItem" look like?

For Each objMail In objCompFolder.Items
If InStr(1, objMail.Subject, strReqID & " - ") > 0 Then
' this is the one to attach
MailItem.Attachments.Add ??????
Exit Sub
End If
Next objMail
 
And would it be objMail ?

For Each objMail In objCompFolder.Items
If InStr(1, objMail.Subject, strReqID & " - ") > 0 Then
' this is the one to attach
MailItem.Attachments.Add objMail
Exit Sub
End If
Next objMail


--
Dmitry Streblechenko (MVP)
http://www.dimastr.com/
OutlookSpy - Outlook, CDO
and MAPI Developer Tool
-
 
When I use objMail, I get an error message "Run-time error '-2147024809
(80070057':
File "the subject line of the email" does not exist.

However, if I hardcode objCompFolder.Items(2), which is the same email, it
works. Here's the code (I'm using redemption to get rid of the messages) :

blnFlag = False
For Each objMail In objCompFolder.Items
If InStr(1, objMail.Subject, rst!id_Request & " - ") > 0 Then
blnFlag = True
Exit For
End If
Next objMail

' Send Mail
Set sMailItem = CreateObject("Redemption.SafeMailItem")
Set oItem = Outlook.CreateItem(0) 'Create a new message
With sMailItem
.Item = oItem
If blnFlag Then .Attachments.Add (objMail)
 
Parenthesis gave the same error.

I changed the find loop instead:
For intTemp = 1 To objCompFolder.Items.Count
If InStr(1, objCompFolder.Items(intTemp).Subject, rst!id_Request & " - ")
' this is the one to attach
blnFlag = True
Exit For
End If
Next intTemp

Now I can refence it as:
If blnFlag Then .Attachments.Add (objCompFolder.Items(intTemp))

for some reason, this works. Thanks for your efforts, anyway!
 
Since you are using late binding in VB, for whatever reason it decided to
pas the default property of the MailItem object, which happens to be
Subject. Attachments.Add saw a string value and assumed it is a file path,
You really need to somehow force the actual object to be passed.
Since you are using VBA, you can dim the object as MailItem:

dim Mail as MailItem
blnFlag = False
For Each objMail In objCompFolder.Items
If InStr(1, objMail.Subject, rst!id_Request & " - ") > 0 Then
set Mail = objMail
MailItem.Attachments.Add(Mail)
Exit For
End If
Next objMail

--
Dmitry Streblechenko (MVP)
http://www.dimastr.com/
OutlookSpy - Outlook, CDO
and MAPI Developer Tool
-
 
Back
Top