Accessing an email attachment as an object - vbscript

OK so I have a script that goes through my outlook inbox looking for a particular header string. This works great for emails directly in my inbox. Now I'm trying to expand this detection to emails that contain other emails as attachments. I've spent significant time researching this and I can't seem to find the proper way to access the email attachment directly. What I've ended up doing is saving the attachment to disc and then reading it back in using CreateItemFromTemplate. I find this to be a cludge solution and I'm hoping someone here can help me find a more elegant way to do this where I can bypass the saveas as CreateItemFromTemplate and directly create an item object from the attachment. Here is proof of concept script I've put together for this:
Const olFolderInbox = 6
Const olMail = 43
Const olEmbeddeditem = 5
Const PropName = "http://schemas.microsoft.com/mapi/proptag/0x007D001E"
Set app = CreateObject("Outlook.Application")
set objNamespace = app.GetNamespace("MAPI")
set objInboxItems = objNameSpace.GetDefaultFolder(olFolderInbox).items
wscript.echo "Have your inbox open checking for fish tests or emails as attachments"
for each objItem in objInboxItems
if objItem.Class = olMail then
with objItem
strHeader = .PropertyAccessor.GetProperty(PropName)
iLoc1 = instr(1,strHeader,"X-Testing",1)
if iLoc1 > 0 then
wscript.echo "mytest. From: " & .Sender & " at: " & .ReceivedTime & " subjet: " & .Subject
end if
iLoc1 = instr(1,strHeader,"X-PHISHTEST",1)
if iLoc1 > 0 then
wscript.echo "Go Fish. From: " & .Sender & " at: " & .ReceivedTime & " subjet: " & .Subject
end if
if .attachments.count > 0 then
set objAttachment = .attachments.item(1)
if objAttachment.type = olEmbeddeditem then
wscript.echo "Has Attachment. From: " & .Sender & " at: " & .ReceivedTime & " subjet: " & .Subject
wscript.echo " - Filename: " & objAttachment.Filename
objAttachment.SaveAsFile ("c:\temp\TempEmail.msg")
set objExtMsg = app.CreateItemFromTemplate("c:\temp\TempEmail.msg")
strExtHeader = objExtMsg.PropertyAccessor.GetProperty(PropName)
iLoc1 = instr(1,strExtHeader,"X-Testing",1)
if iLoc1 > 0 then wscript.echo " ++ This is a plain test message"
end if
end if
end with
end if
next
wscript.echo "That's all folks" `

That is the best you can do in OOM alone - save the attachment as an MSG file and then reopen it. OpenSharedItem is a better way to open an MSG file than CreateItemFromTemplate.
On the Extended MAPI level (C++ or Delphi), you can open the PR_ATTACH_DATA_OBJ property as IMessage using IAttach::OpenProperty. If Extended MAPI is not an option, you can use Redemption (I am its author - any language) - both Safe*Item and RDO families of objects expose EmbeddedMsg property on the attachment object that return the attachment message.

Related

Expected statement error at Line 1 Char 1 for example script

I'm completely new to scripting and am trying to mess around with it and start learning. I've done a couple WScript.Echo commands displaying a message or adding two numbers. I copied the below code from a MS article I was reading on the Echo method.
It seems it is having issues with <package>. Is this an unacceptable way to start a script? What else would I need to do to get this example code to work on my machine?
Also, can't get the code to post in my question. Indenting 4 spaces doesn't do anything.
The sample code in that article is for .wsf files, not for .vbs files. If you want to use the latter: strip the XML tags from the sample code and it should work.
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives
Set oPrinters = WshNetwork.EnumPrinterConnections
WScript.Echo "Domain = " & WshNetwork.UserDomain
WScript.Echo "Computer Name = " & WshNetwork.ComputerName
WScript.Echo "User Name = " & WshNetwork.UserName
WScript.Echo
WScript.Echo "Network drive mappings:"
For i = 0 to oDrives.Count - 1 Step 2
WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
Next
WScript.Echo
WScript.Echo "Network printer mappings:"
For i = 0 to oPrinters.Count - 1 Step 2
WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
Next

How to send lotus notes mail with VB script with other mail box

Hi I am sending lotus notes mail with VB script . Now I want to send mail with other mail box which is opened in my lotus notes instead of my mail box. I tried different options but no luck. I am using below code to send mail.
You can find the code in below URL:
https://gallery.technet.microsoft.com/scriptcenter/fe141119-9599-46a7-90ca-8dbc66d50297
option explicit
' --------------------------------------------------------------------------
' -- Create Lotus Notes email (and add attachment) using VB Script
' --
' -- Version 1.01
' --
' -- Created by : Michael Green
' -- migreen#westpac.com.au
' --
' -- Based on in-complete/partially working script from :
' -- http://en.allexperts.com/q/Using-Lotus-Notes-1427/Creating-LotusNotes-email-using-1.htm
' --
' -- Created : 06/10/2009
' -- Last Updated: 07/10/2009
' --------------------------------------------------------------------------
Dim oSession ' AS NotesSession
Dim strServer
Dim strUserName
Dim strMailDbName
Dim oCurrentMailDb ' as NOTESDATABASE
Dim oMailDoc ' as NOTESDOCUMENT
Dim ortItem ' as NOTESRICHTEXTITEM
Dim ortAttacment ' as NOTESRICHTEXTITEM
Dim oEmbedObject ' as ????
dim cstrAttachment
Dim blAttachment
cstrAttachment = "c:\Temp\Telstra.xls"
blAttachment = True
' Start a session to notes
wscript.echo "## Connecting to Lotus Notes session..."
Set oSession = CreateObject("Notes.NotesSession")
wscript.echo("NotesVersion : " & oSession.NotesVersion)
wscript.echo("NotesBuildVersion: " & oSession.NotesBuildVersion)
wscript.echo("UserName : " & oSession.UserName)
wscript.echo("EffectiveUserName: " & oSession.EffectiveUserName)
wscript.echo "## GetEnvironmentString..."
strServer = oSession.GetEnvironmentString("MailServer",True)
wscript.echo("Server :" & strServer)
' eg. CN=Michael V Green/OU=CORPAU/OU=WBCAU/O=WBG
strUserName = oSession.UserName
strMailDbName = Left(strUserName, 1) & Right(strUserName, (Len(strUserName) - InStr(1, strUserName, "")))&".nsf"
wscript.echo("MailDbName :" & strMailDbName)
wscript.echo "## Getting current Notes database..."
' open the mail database in Notes
set oCurrentMailDb = oSession.CurrentDatabase
wscript.echo("fileName:" & oCurrentMailDb.fileName)
wscript.echo("filePath:" & oCurrentMailDb.filePath)
wscript.echo("server:" & oCurrentMailDb.server)
wscript.echo("Title:" & oCurrentMailDb.Title)
If oCurrentMailDb.IsOpen = True Then
' Already open for mail
wscript.echo "## Lotus Notes mail database is already open !"
Else
wscript.echo "## Opening Lotus Notes mail database..."
oCurrentMailDb.OPENMAIL
End If
' Create a document in the back end
Set oMailDoc = oCurrentMailDb.CREATEDOCUMENT
' Set the form name to memo
OMailDoc.form = "Memo"
with oMailDoc
.SendTo = "migreen#westpac.com.au"
.BlindCopyTo = "mgreen#ozemail.com.au"
.CopyTo = "migreen#westpac.com.au"
.Subject = "This is a test of VB scripting driving Lotus Notes 7 "
end with
set ortItem = oMaildoc.CREATERICHTEXTITEM("Body")
with ortItem
.AppendText("Test of RTF Item append")
.AddNewLine(2)
.AppendText("Signature")
End With
' Create additional Rich Text item and attach it
If blAttachment Then
Set ortAttacment = oMailDoc.CREATERICHTEXTITEM("Attachment")
' Function EMBEDOBJECT(ByVal TYPE As Short, ByVal CLASS As String, ByVal SOURCE As String, Optional ByVal OBJECTNAME As Object = Nothing) As Object
' Member of lotus.NOTESRICHTEXTITEM
Set oEmbedObject = ortAttacment.EMBEDOBJECT(1454, "", cstrAttachment, "Attachment")
End If
wscript.echo "## Sending email..."
with oMailDoc
.PostedDate = Now()
.SAVEMESSAGEONSEND = "True"
.send(false)
end with
wscript.echo "## Sent !"
' close objects
set oMailDoc = nothing
set oCurrentMailDb = nothing
set oSession = nothing
Just replace the lines (that are complete nonsense, but I told you in the other post):
strMailDbName = Left(strUserName, 1) & Right(strUserName, (Len(strUserName) - InStr(1, strUserName, "")))&".nsf"
wscript.echo("MailDbName :" & strMailDbName)
wscript.echo "## Getting current Notes database..."
' open the mail database in Notes
set oCurrentMailDb = oSession.CurrentDatabase
wscript.echo("fileName:" & oCurrentMailDb.fileName)
wscript.echo("filePath:" & oCurrentMailDb.filePath)
wscript.echo("server:" & oCurrentMailDb.server)
wscript.echo("Title:" & oCurrentMailDb.Title)
If oCurrentMailDb.IsOpen = True Then
' Already open for mail
wscript.echo "## Lotus Notes mail database is already open !"
Else
wscript.echo "## Opening Lotus Notes mail database..."
oCurrentMailDb.OPENMAIL
End If
with
strServer = "ServerNameWhereMailboxIs"
strMailDbName = "mail\nameofotherdatabase.nsf"
set oCurrentMailDb = oSession.GetDatabase( strServer, strMailDbName )
That will do the trick.
As your question changed after my answer, I will -for the sake of anybody finding this question in the future- add some code for "sending an email in the name of another sender":
In Lotus Notes it is not possible to "send" a mail without leaving traces of the person who really sent it:
When you receive such a mail, that was sent by someone else you will see, that the mail comes from the other mailbox, but it will contain the information "Sent by" with the mailaddress of the "real" sender.
To at least make the "visual" sender look right, you need to add different fields that are needed in different cases: These fields are Principal, InetPrincipal, From and InetFrom.
However: On a Domino- Server that is configured right, this will not help: It will calculate these fields from the "real" sender and ignore what you gave him.
But there is a trick to make the router leave these fields alone: You have to add the NotesDomain to the adressen. If you add the following lines to your code, then the router will ignore these and keep the fields intact:
MailDoc.principal = "noreply#company.com#NotesDomain"
MailDoc.inetprincipal = "noreply#company.com#NotesDomain"
MailDoc.from = "noreply#company.com#NotesDomain"
MailDoc.inetfrom = "noreply#company.com#NotesDomain"
If you really need to "hide" the real sender completely from the recipient, then you cannot create the mail in the mail database, but create it directly in the "mail.box" of the server and just "Save" it instead of "Send" it. But this has other downsides and will not be discussed here.
I just want to leave one more answer about "send from/reply to" because this question here is what I found when I was searching for help:
I found out that only my own mailadress is shown to external recipients or people not using IBM notes. Even if I sent mails via a different mailfile (a Mail-In) only my own mailadress was shown and I also was the one the recipient could reply to. So I tried something, and it worked.
After some testing, this lines helped me out internal and external:
sender = """John Doe""" & "<support#domain.de>"
MailDoc.ReplyTo = sender
MailDoc.SMTPOriginator = sender
MailDoc.sender = sender
MailDoc.principal = sender
MailDoc.inetprincipal = sender
MailDoc.from = sender
MailDoc.inetfrom = sender
MailDoc.displayfrom = sender

Is there a way to detect if Outlook message does NOT have an attachment?

Ive been looking for a solution to this for a while now and need a bit of help.
I need to detect when someone sends me a message to my outlook account when it does not have attachents.
I have a situation that.
An email is sent to me
There is spacific text in the subject
It has an attachment
If it has an attachment it sends reply 1 and moves the message to folder A
If it does not have an attachmnet it sends reply 2.and moves the message into folder B
Any help would be welcome
Many thanks
You can do this very easily in VBScript, like so:
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim m As Variant
Dim strBody As String
Dim intIn As Long
Dim intAttachCount As Integer, intStandardAttachCount As Integer
On Error GoTo handleError
'Edit the following line if you have a signature on your email that includes images or other files. Make intStandardAttachCount equal the number of files in your signature.
intStandardAttachCount = 0
strBody = LCase(Item.Body)
intIn = InStr(1, strBody, "original message")
If intIn = 0 Then intIn = Len(strBody)
intIn = InStr(1, Left(strBody, intIn), "attach")
intAttachCount = Item.Attachments.Count
If intIn > 0 And intAttachCount <= intStandardAttachCount Then
m = MsgBox("It appears that you mean to send an attachment," & vbCrLf & "but there is no attachment to this message." & vbCrLf & vbCrLf & "Do you still want to send?", vbQuestion + vbYesNo + vbMsgBoxSetForeground)
If m = vbNo Then Cancel = True
End If
handleError:
If Err.Number <> 0 Then
MsgBox "Outlook Attachment Reminder Error: " & Err.Description, vbExclamation, "Outlook Attachment Reminder Error"
End If
End Sub
This can be modified for your exact need, but it's pretty straightforward.
Simple Google search away. Give credit to the guy who wrote it.

Internal Server Error with VB script

I'm trying to send an email with VB script/ASP (I don't normally use this language but this is what the site is built in), and it is throwing a 500 error.
I'm not seeing what I did wrong. Everything looks like it should execute to me. Any ideas?
<%
dim name
dim from
dim company
dim phone
dim zip
dim message
dim areas
name = Request.Form("name")
from = Request.Form("from")
company = Request.Form("company")
phone = Request.Form("phone")
zip = Request.Form("zip")
areas = Request.Form("areas")
message = Request.Form("message")
Dim Mail, strHost
Dim strSubject, strBody, strPath
strHost = "localhost"
Set Mail = Server.CreateObject("Persits.MailSender")
Mail.Host = strHost
Mail.From = "cphelps#client.com"
Mail.FromName = "Client Name"
Mail.AddAddress "cphelps#client.com"
If Not InStr(from, "domain.com") Then Mail.AddBcc "cphelps#client.com"
Mail.Subject = name & " sent a request"
Mail.Body = name & "," & vbCrLf & vbCrLf &_
"Name:" & name & vbCrLf &_
"Company: " & company & vbCrLf &_
"From: " & from & vbCrLf &_
"Phone: " & phone & vbCrLf &_
"Zip Code: " & zip & vbCrLf &_
"Message: " & message & vbCrLf &_
Mail.Send
Response.Redirect("jlg_thank_you.asp")
set Mail = nothing
%>
The first thing I noticed is that you are missing an End If in the code sample provided.
I disabled Friendly error messages and I attempted to run the code and got this error:
Server object error 'ASP 0177 : 800401f3'
Server.CreateObject Failed
/test.asp, line 26
800401f3
On researching this error I found someone with a similar problem:
Server.createObject with Persist.Mailsender error
They suggested that its a missing dll problem.
For my projects I have used Server.CreateObject("CDO.Message")
Here is an example of my code:
Set mail = Server.CreateObject("CDO.Message")
mail.To = varTo
mail.From = varFrom
mail.Subject = varSubject
mail.HTMLBody = varBody
mail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
mail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.domain.com"
mail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
mail.Configuration.Fields.Update
mail.Send
Make sure you downloaded the latest version of ASPEmail and that it is present on the server running the script.
Also, register it using this command line:
regsvr32 c:\path\aspemail.dll

Autogenerate an email in an outlook and attach the currently open word document with VBS

I want to write a VBS macro to auto generate an email in outlook and attach a word document. I currently have a macro that does this for excel, but I can't get it to work for Word. I can't figure out for the life of me what my "FName= " should be. Any suggestions or help would be greatly appreciated. Here is what I have:
Sub AutoEmail()
On Error GoTo Cancel
Dim Resp As Integer
Resp = MsgBox(prompt:=vbCr & "Yes = Review Email" & vbCr & "No = Immediately Send" & vbCr & "Cancel = Cancel" & vbCr, _
Title:="Review email before sending?", _
Buttons:=3 + 32)
Select Case Resp
'Yes was clicked, user wants to review email first
Case Is = 6
Dim myOutlook As Object
Dim myMailItem As Object
Set otlApp = CreateObject("Outlook.Application")
Set otlNewMail = otlApp.CreateItem(olMailItem)
FName = ActiveWord & "\" & ActiveWord.Name
With otlNewMail
.To = ""
.CC = ""
.Subject = ""
.Body = "Good Morning," & vbCr & vbCr & "" & Format(Date, "MM/DD") & "."
.Attachments.Add FName
.Display
End With
Set otlNewMail = Nothing
Set otlApp = Nothing
Set otlAttach = Nothing
Set otlMess = Nothing
Set otlNSpace = Nothing
'If no is clicked
Case Is = 7
Dim myOutlok As Object
Dim myMailItm As Object
Set otlApp = CreateObject("Outlook.Application")
Set otlNewMail = otlApp.CreateItem(olMailItem)
FName = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
With otlNewMail
.To = ""
.CC = ""
.Subject = ""
.Body = "Good Morning," & vbCr & vbCr & " " & Format(Date, "MM/DD") & "."
.Attachments.Add FName
.Send
'.Display
'Application.Wait (Now + TimeValue("0:00:01"))
'Application.SendKeys "%s"
End With
'otlApp.Quit
Set otlNewMail = Nothing
Set otlApp = Nothing
Set otlAttach = Nothing
Set otlMess = Nothing
Set otlNSpace = Nothing
'If Cancel is clicked
Case Is = 2
Cancel:
MsgBox prompt:="No Email has been sent.", _
Title:="EMAIL CANCELLED", _
Buttons:=64
End Select
End Sub
May it is a bit late, but I want to solve it for future use.
You want to have the active document as your file name (FName).
FName = Application.ActiveDocument.Path + "\" + Application.ActiveDocument.Name
' .Path returns only the Path where the file is saved without the file name like "C:\Test"
' .Name returns only the Name of the file, including the current type like "example.doc"
' Backslash is needed because of the missing backslash from .Path
otlNewMail.Attachements.Add FName
May you also want to save your current document before sending it via outlook, otherwise you will send the document without the changes made.
Function SaveDoc()
ActiveDocument.Save
End Function
I hope that this will help others, because the code from the question helped me a lot while scripting a similar script.

Resources