简体   繁体   English

Outlook VBA - 分别保存附件和电子邮件

[英]Outlook VBA - Save Attachments and Email separately

User will select an Email and I need to save all its attachments to a folder + that Email without attachment in a separate folder.用户将选择一封电子邮件,我需要将其所有附件保存到一个文件夹+该电子邮件没有附件在一个单独的文件夹中。

I have written code and it seems to be working fine except one big issue:我已经编写了代码,它似乎工作正常,除了一个大问题:

Attachments are removed from original email also from my Inbox.附件也会从我的收件箱中从原始电子邮件中删除。 After removing attachments I am calling SaveAs method so I think this should not happen.删除附件后,我正在调用 SaveAs 方法,所以我认为这不应该发生。

Here is the code I have written:这是我写的代码:

 Dim objMailItemOriginal As Outlook.MailItem
    Dim objMailItemNew As Outlook.MailItem
    Dim objNameSpaceUserNS As Outlook.namespace
    Dim emailPath$, tmpFolder$

    Set objMailItemOriginal = Application.ActiveExplorer.Selection(1)
    Set objMailItemNew = Application.CreateItem(olMailItem)
    Set objNameSpaceUserNS = Application.GetNamespace("MAPI")

    tmpFolder = Environ("Temp") & "\" & Format$(Now, "hh_mm_ss")
    MkDir tmpFolder

    emailPath = Environ$("Temp") & "\tmpEmail.msg"

    Dim attachPath$
    For i = objMailItemOriginal.Attachments.Count To 1 Step -1
        attachPath = tmpFolder & "\" & objMailItemOriginal.Attachments(i)
        objMailItemOriginal.Attachments(i).SaveAsFile attachPath

        objMailItemNew.Attachments.Add attachPath
        objMailItemOriginal.Attachments.Remove (i)
    Next

    objMailItemOriginal.SaveAs emailPath
    objMailItemOriginal.Close olDiscard

Any outlook expert please?请问有什么前景专家吗?

only way I can think of would be to save the E-Mail including attachments, then open the saved E-Mail from the disk and work with the attachments in there.我能想到的唯一方法是保存包含附件的电子邮件,然后从磁盘打开保存的电子邮件并使用其中的附件。

Sub workwithmail(pathfile As string)
Dim oNamespace As Outlook.NameSpace
 Set oNamespace = Application.GetNamespace("MAPI")
Dim oSharedItem As Outlook.mailitem
Dim pathfile As String
    Set oSharedItem = oNamespace.OpenSharedItem(pathfile)

  '''here Comes your code

    oSharedItem.Close (olSave)
    Set oSharedItem = Nothing
    Set oNamespace = Nothing
End Sub

Do not delete the attachments from the original item.不要从原始项目中删除附件。 Save the message as an MSG file using MailItem.SaveAs, reopen it using Application.Session.OpenSharedItem (returns MailItem object) and remove attachments from that object.使用 MailItem.SaveAs 将消息保存为 MSG 文件,使用 Application.Session.OpenSharedItem 重新打开它(返回 MailItem 对象)并从该对象中删除附件。 Then call MailItem.Save.然后调用 MailItem.Save。

To lower the size of the file without the attachments you could do this:要减小没有附件的文件大小,您可以这样做:

oSharedItem.SaveAs "filePath here"
oSharedItem.Close olDiscard

Then the attachments are still in the original mail in the outlook explorer and the saved file is smaller.然后附件还在outlook explorer的原始邮件中,保存的文件变小了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM