vba to secure zip attachments

Post number 3 has been selected as the best answer.

Status
Not open for further replies.

shrydvd

New Member
Outlook version
Outlook 2019 64-bit
Email Account
IMAP
I am hoping someone can pull me out of this . . . I am trying to identify emails that have attachments then zip those attachments together with a password. I end up with different errors but can't seem to get it. One of the main errors is with PKZip in the command line saying "Nothing to do". I am sure it has something to do with how I am trying to tell it which files to zip.

Anyway, here is what I have. It is a mixed bag of pieces I have gotten elsewhere and trying to put them together.

If I am way off base and need to scrap it & start over, please tell me that as well. Also, there is likely extraneous junk in the code below simply because I keep trying different things.

Thank you for any guidance you can provide.
Code:
Sub ZipdAttach()

    Dim objMail As Outlook.MailItem
    Dim objAttachments As Outlook.Attachments
    Dim objAttachment As Outlook.Attachment
    Dim objFileSystem As Object
    Dim objShell As Object
    Dim varTempFolder As Variant
    Dim varZipFile As Variant
    Dim myDir As String
    Dim dest As Variant
    Dim srce As Variant
    Dim strCommand As String
    Dim val As String
    'Save the attachments to Temporary folder
    Set objFileSystem = CreateObject("Scripting.FileSystemObject")
    varTempFolder = objFileSystem.GetSpecialFolder(2).Path & "\Temp " & Format(Now, "dd-mm-yyyy- hh-mm-ss-")
    MkDir (varTempFolder)
    varTempFolder = varTempFolder & "\"
 
    Set objMail = Outlook.Application.ActiveInspector.CurrentItem
    Set objAttachments = objMail.Attachments
    For Each objAttachment In objAttachments
        objAttachment.SaveAsFile (varTempFolder & objAttachment.FileName)
    Next
 
   'Create a new zip file
    varZipFile = InputBox("Specify a name for the new zip file", "Name Zip File", objMail.Subject)
    varZipFile = varTempFolder & varZipFile
 
    'Copy all the saved attachments to the new zip file
     Set objShell = CreateObject("Shell.Application")
    
'_______________________________________________


val = InputBox("Give me an 8 character password.")
myDir = "C:\Program Files\PKWARE\PKZIPC"
dest = varZipFile
srce = varTempFolder
strCommand = "pkzipc.exe -add -passphrase=" & val & " " & dest & " " & srce
Call Shell("cmd.exe /k cd /d " & myDir & " & " & strCommand, 1)

End Sub
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
>> Also, there is likely extraneous junk in the code below simply because I keep trying different things.
LOL. A lot of my code has unnecessary junk in it for the same reason.

Try this change:
srce = varTempFolder & *.*

From the way i read the documentation, it should add the folder contents when you use just the folder, but designating all files in the folder works here.
 
Last edited:

shrydvd

New Member
Outlook version
Outlook 2019 64-bit
Email Account
IMAP
I'm sorry I didn't get back with you to say thank you. When I tried your answer, it worked great & I got carried away with the rest of the project. Anyway, while I am sure my code is "less than elegant" to say the least, this works for me if it will help someone else.
Thank you again to Diane for her guidance that made it all finally work!


Code:
Sub ZipAttach()
    Dim objMail As Outlook.MailItem
    Dim objAttachments As Outlook.Attachments
    Dim objAttachment As Outlook.attachment
    Dim objFileSystem As Object
    Dim varTempFolder As String
    Dim varzipfile As String
    Dim val As String
    Dim n As String
    Dim srce As String
    Dim dest As String
'    Dim sender As Outlook.AddressEntry
 
    n = (Format(Now, "dd-mm-yyyy- hh-mm-ss-")) 'the folder name where attachments are saved & converted
EnterVal:
    val = InputBox("Create password of at least 8 characters.")
            If StrPtr(val) = 0 Then 'Cancel was pressed
            ' Handle what to do if cancel pressed
            Exit Sub
            ElseIf Len(strM) < 8 Then 'Not enough characters entered
            MsgBox "You must enter at least 8 characters."
            GoTo EnterVal
            End If

       'Save the attachments to Temporary folder
    Set objFileSystem = CreateObject("Scripting.FileSystemObject")
    varTempFolder = objFileSystem.GetSpecialFolder(2).Path & "\Temp " & n
    MkDir (varTempFolder)
    varTempFolder = varTempFolder & "\"
 
    Set objMail = Outlook.Application.ActiveInspector.CurrentItem
    Set objAttachments = objMail.Attachments
    For Each objAttachment In objAttachments
        objAttachment.SaveAsFile (varTempFolder & objAttachment.FileName)
    Next
    dest = "protectedfiles.zip"
    srce = """" & varTempFolder & "*.*" & """"
    Cmd2 = "CD " & varTempFolder
    cmd3 = "pkzipc.exe -add -passphrase=" & val & " " & "protectedfiles.zip" & " " & srce
    
    Connector = " & "
    Commands = "cmd.exe /c " & Cmd2 & Connector & cmd3
    Debug.Print Commands
    pid = Shell(Commands, vbNormalFocus)
    
Set objAttachments = objMail.Attachments
     While objAttachments.Count > 0
           objAttachments.Item(1).Delete
     Wend

varzipfile = varTempFolder & "protectedfiles.zip"
Pause (2)
objMail.Attachments.Add varzipfile
'DelFolder (varTempFolder)
'Get the address of the person you are sending to
        Dim olObj As Object
        Set olObj = Application.ActiveInspector.CurrentItem
        olObj.Recipients.Item(1).Resolve
        TheMail = olObj.Recipients.Item(1).Address
        Set olObj = Nothing
'Now, email yourself the password
    Dim s As String
    Dim obApp As Object
    Dim NewMail As MailItem
    Set obApp = Outlook.Application
    Set NewMail = obApp.CreateItem(olMailItem)

User = CreateObject("Outlook.Application").GetNamespace("MAPI").CurrentUser.Address
    'You can change the concrete info as per your needs
    With NewMail
         .Subject = TheMail & " Password Sent " & n
         .To = User
         .Body = "Password used was " & """" & val & """"
         '.Attachments.Add ("C:\Attachments\Test File.docx")
         '.Importance = olImportanceHigh
         .Send
    End With
 
    Set obApp = Nothing
    Set NewMail = Nothing
End Sub
Public Sub Pause(Seconds As Single)
    Dim TimeEnd As Single
    TimeEnd = Timer + Seconds
    While Timer < TimeEnd
        DoEvents
    Wend
End Sub

I will eventually clean it up as much as my novice self can do. I will then replace this with the cleaned up version.
 

Lewis-H

Senior Member
Outlook version
Outlook 2016 64 bit
Email Account
Office 365 Exchange
I suggest you change the program a little and test command in the command prompt. Once you have that working try it in VBA. I added quotes around program exe since it has space.
Sub Zip_Test1()

Dim source As String, Mstr As String, target As String, password As String
Dim file As Variant
Dim cmd As String

Application.DisplayAlerts = False
Mstr = "C:\Users\Desktop\Test"

For Each file In CreateObject("Scripting.FileSystemObject").GetFolder(Mstr).Files
source = Chr$(34) & "C:\Users\Desktop\Test\" & file.Name & Chr$(34)

target = "C:\Users\Desktop\Zipped\"
password = Chr$(34) & "Abcd1234" & Chr$(34)
cmd = """" & "C:\Program Files\PKWARE\PKZIPW\pkzipw.exe" & """" & " -add -pass=" & password & " " & target & " " & source
Debug.Print cmd '' Copy command in Immediate window and paste in Command Prompt.

Shell (cmd)

Exit Sub ''Exit for testing
Next
Application.DisplayAlerts = True
End Sub

Hope this helps!
Regards,
Lewis
 
Status
Not open for further replies.
Similar threads
Thread starter Title Forum Replies Date
A Outlook 2010 VBA fails to launch Outlook VBA and Custom Forms 2
richardwing Outlook 365 VBA to access "Other Actions" menu for incoming emails in outlook Outlook VBA and Custom Forms 0
W Create a Quick Step or VBA to SAVE AS PDF in G:|Data|Client File Outlook VBA and Custom Forms 1
J Outlook Rules VBA Run a Script - Multiple Rules Outlook VBA and Custom Forms 0
C Outlook (desktop app for Microsoft365) restarts every time I save my VBA? Using Outlook 0
D VBA Macro to Print and Save email to network location Outlook VBA and Custom Forms 1
TedSch Small vba to kill political email Outlook VBA and Custom Forms 3
E Outlook 365 Outlook/VBA Outlook VBA and Custom Forms 11
N VBA Macro To Save Emails Outlook VBA and Custom Forms 1
Z VBA Forward vs manual forward Outlook VBA and Custom Forms 2
J VBA Cannot programmatically input or change Value for User Defined field Using Outlook 1
J VBA for outlook to compare and sync between calendar Outlook VBA and Custom Forms 1
A Any way to force sort by/group by on search results with VBA? Outlook VBA and Custom Forms 1
E Default shape via VBA Outlook VBA and Custom Forms 4
A Change settings Send/receive VBA Outlook VBA and Custom Forms 0
Z Import Tasks from Access Using VBA including User Defined Fields Outlook VBA and Custom Forms 0
E Outlook VBA change GetDefaultFolder dynamically Outlook VBA and Custom Forms 6
justicefriends How to set a flag to follow up using VBA - for addressee in TO field Outlook VBA and Custom Forms 11
M add new attendee to existing meetings with VBA Outlook VBA and Custom Forms 5
D VBA code to select a signature from the signatures list Outlook VBA and Custom Forms 3
D Create advanced search (email) via VBA with LONG QUERY (>1024 char) Outlook VBA and Custom Forms 2
David McKay VBA to manually forward using odd options Outlook VBA and Custom Forms 1
FryW Need help modifying a VBA script for in coming emails to auto set custom reminder time Outlook VBA and Custom Forms 0
S vba outlook search string with special characters Outlook VBA and Custom Forms 1
S VBA search string with special characters Outlook VBA and Custom Forms 1
U Outlook 2019 VBA run-time error 424 Outlook VBA and Custom Forms 2
DDB VBA to Auto Insert Date and Time in the signature Outlook VBA and Custom Forms 2
F VBA to move email from Non Default folder to Sub folders as per details given in excel file Outlook VBA and Custom Forms 11
G VBA to save selected Outlook msg with new name in selected network Windows folder Outlook VBA and Custom Forms 1
F Excel VBA to move mails for outlook 365 on secondary mail account Outlook VBA and Custom Forms 1
B Zoom automatically next email item (VBA) Outlook VBA and Custom Forms 2
T vba extract data from msg file as attachment file of mail message Outlook VBA and Custom Forms 1
K Outlook Office 365 VBA download attachment Outlook VBA and Custom Forms 2
A VBA Script - Print Date between first email in Category X and last email in Category Y Outlook VBA and Custom Forms 3
N Help creating a VBA macro with conditional formatting to change the font color of all external emails to red Outlook VBA and Custom Forms 5
N Save selected messages VBA does not save replies and/or messages that contain : in subject Outlook VBA and Custom Forms 1
Y Filter unread emails in a search folder vba help Outlook VBA and Custom Forms 0
V vBA for searching a cell's contents in Outlook and retrieving the subject line Outlook VBA and Custom Forms 1
B vBA for exporting excel file from outlook 2016 Outlook VBA and Custom Forms 3
L Modifying VBA script to delay running macro Outlook VBA and Custom Forms 3
L Need help modifying a VBA script for emails stuck in Outbox Outlook VBA and Custom Forms 6
K can't get custom form to update multiple contacts using VBA Outlook VBA and Custom Forms 3
S Excel vba code to manage outlook web app Using Outlook 10
H Custom Outlook Contact Form VBA Outlook VBA and Custom Forms 1
S Problem Checking the available stores in my Inbox (Outlook VBA) Outlook VBA and Custom Forms 0
S Outlook VBA How to adapt this code for using in a different Mail Inbox Outlook VBA and Custom Forms 0
S Add VBA save code Using Outlook 0
C Auto Run VBA Code on new email Outlook VBA and Custom Forms 1
O VBA Cases with Listbox - Can you use Multi-Select? Outlook VBA and Custom Forms 4
O VBA Outlook Message Attachment - Array Index Out of Bounds Outlook VBA and Custom Forms 0

Similar threads

Top