Extracting email into pdf format (1 Viewer)

Derek

Registered User.
Local time
Today, 12:05
Joined
May 4, 2010
Messages
234
Hi guys

I want to use outlook vba to save the email down as .pdf format . There is a 'Apps' folder within the mailbox so all the emails in that mailbox need to be converted into .pdf file and save down in a dedictaed folder . To note there are no attachments in the emails so just the body message needs to be converted to .pdf.

There needs to be a separate .pdf file for each email . Can anyone please help me with this ?

Thanks a lot for your help.
 

sxschech

Registered User.
Local time
Today, 12:05
Joined
Mar 2, 2010
Messages
792
I had seen some of those links a while ago and couldn't quite seem to get them to work with my code. Decided to revisit and try again. Eventually I found an example at the DataNumen site, while similar to the other examples, had some keywords that helped me sort it out. One was that it mentioned assigning-specific-color-category. I then realized I already had code to change flag status, so then was able to modify the datanumen code to work with my code. Posting my code solution below in case may be helpful to others. Also, a recent thread mentioned Daniel Pineault, and that reminded me I had downloaded some of his code that I thought might be useful at some point and turns out to fit nicely in this situation.

Couple of notes:
  • Uses late binding so should not need to set up any references
  • I have commented out the lines of code that opens a form for editing the file name so that I don't have to attach my form as a file. Since this area of the code deals with how the file will be named, may need to adjust this code. Currently defaults to the User's downloads folder
  • In my use, the email search is based on passing the data from a form containing a query of outlook messages, so would either need to link or download outlook data or have some other way to obtain the exact subject name and date sent in order to feed that data into the function
  • The outlook data being retrieved is in a shared mailbox, so would need to edit that line of code to point to the mailbox where your messages reside
  • These code sub/functions would be saved in a standard module and called from your form or other process
  • Edited to add a few additional functions for the file naming
Code:
Public Function SaveMessageAsPDF(Subj As String, dtsent As Date)
'Changed Extract Attachment Code to change the flag status
'https://stackoverflow.com/questions/15531093/save-attachments-to-a-folder-and-rename-them
'https://www.experts-exchange.com/questions/28545501/Outlook-VBA-set-flag.html
'Refer to that function for notes and original links
'Combined with new code from Datanumen
'https://www.datanumen.com/blogs/auto-save-email-pdf-file-assigning-specific-color-category/
'Looked at other versions mentioned via https://www.access-programmers.co.uk/forums/threads/extracting-email-into-pdf-format.312163/
'such as website: https://www.howto-outlook.com/howto/saveaspdf.htm
'and https://www.extendoffice.com/documents/outlook/5036-batch-convert-outlook-emails-to-pdf.html#a2
'but found the one from DataNumen was able to be adapted to the existing code without having
'as many debug issues.
'20200615 
    Dim OlApp As Object                 'Late
    Dim Inbox As Object
    Dim InboxItems As Object
    Dim Mailobject As Object
    Dim SubjectFilter As String
    Dim FSO As Object
    Dim TmpFolder As Object
    Dim stOldName As String
    Dim stNewName As String
    Dim stFilePath As String
  
    On Error Resume Next
    Set FSO = CreateObject("scripting.filesystemobject")
    Set OlApp = GetObject(, "Outlook.Application")      'Outlook Running
  
    If Err.Number <> 0 Then
        Err.Clear
        Set OlApp = CreateObject("Outlook.Application")
    End If
  
    'Doc Control Inbox
    Set Inbox = OlApp.GetNamespace("Mapi").Folders("Shared Mailbox").Folders("Inbox") 'EDIT THIS TO YOUR INBOX LOCATION
    Set InboxItems = Inbox.Items
  
    SubjectFilter = (Subj)  '("Fwd: Data and Message for Review") ' THIS IS WHERE YOU PLACE THE EMAIL SUBJECT FOR THE CODE TO FIND

    If Not Inbox Is Nothing Then
        For Each Mailobject In InboxItems
            If InStr(1, Mailobject.Subject, SubjectFilter) > 0 And InStr(1, Mailobject.senton, dtsent) > 0 Then
                stOldName = Mailobject.Subject
                stNewName = stOldName
                'Remove the unsupported characters in the email subject
                stNewName = Replace(stNewName, "/", " ")
                stNewName = Replace(stNewName, "\", " ")
                stNewName = Replace(stNewName, ":", " ")
                stNewName = Replace(stNewName, "?", " ")
                stNewName = Replace(stNewName, Chr(34), " ")
                stNewName = Replace(Format(Mailobject.ReceivedTime, "yyyymmdd") & " " & stNewName, "  ", " ")
'                DoCmd.OpenForm "frmEditText", , , , , acDialog, "Renaming file.  " & _
                                                    "Please review and adjust accordingly if the text needs futher editing.|Rename File|NoTimer|" & stOldName & "|" & stNewName
'                stNewName = gblText
                'Firstly, save the email as a mht file in the temporary folder
                stFilePath = FSO.GetSpecialFolder(2) & "\" & stNewName & ".mht"
                Mailobject.SaveAs stFilePath, 5 'olMHTML
                'Open the mht file in MS Word and export as a PDF file
                Call PrintWordDoc(stFilePath, Environ("USERPROFILE") & "\Downloads\") 'EDIT THIS TO YOUR SAVE AS LOCATION
            End If
        Next
    End If

    Set OlApp = Nothing
    Set Inbox = Nothing
    Set InboxItems = Nothing
    Set Mailobject = Nothing
End Function

Sub PrintWordDoc(sfile As String, Optional sSavePath As String)
'Example of how to save a word doc to pdf
'
'---------------------------------------------------------------------------------------
' Procedure : PrintWordDoc
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Print/Save a Word document as a PDF in the specified directory
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFile     : Full path, filename and extension of the word document to convert to a PDF
' sSavePath : Path where you would like the PDF saved to
'
' Usage:
' ~~~~~~
' Call PrintWordDoc("C:\Users\Dev\Documents\Test.doc", "C:\Users\Dev\Desktop\")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2016-02-01                  Initial Release
'---------------------------------------------------------------------------------------
'https://www.devhut.net/2016/02/01/vba-save-a-word-document-as-a-pdf/
'20181108
'Made sSavePath optional so that only need to provide if want to
'save the file to a different location.  Only need to provide the
'file name if saving to the same location and program will use
'that path for saving to pdf
'20190503

    Dim oApp                  As Object
    Dim oDoc                  As Object
    Dim sFileName             As String
    Dim bAppAlreadyOpen       As Boolean

    bAppAlreadyOpen = True
    'Get an instance of word to work with
    'See if Word is already running
    On Error Resume Next
    Set oApp = GetObject(, "Word.Application")
    If Err.Number <> 0 Then
        'Launch a new instance of Word
        Err.Clear
        On Error GoTo Error_Handler
        Set oApp = CreateObject("Word.Application")
        bAppAlreadyOpen = False
    End If  
    'Determine the Word doc filename without the path or extension
    'sFileName = Right(sfile, Len(sfile) - InStrRev(sfile, "\"))
    'sFileName = Left(sFileName, InStr(sFileName, ".") - 1)
    'Above code caused problems when there are extra periods/dots in the file name
    'so using the function instead
    '20200616
    sFileName = FileNameNoExt(sfile)
    If Len(sSavePath) = 0 Then
        sSavePath = FILEPATH(sfile)
    End If
    'Ensure the path has the final \
    If Right(sSavePath, 1) <> "\" Then sSavePath = sSavePath & "\"
    'Open the document
    Set oDoc = oApp.Documents.Open(sfile)
    'Print the document as a PDF
    oDoc.ExportAsFixedFormat sSavePath & sFileName & ".pdf", 17

Error_Handler_Exit:
    On Error Resume Next
    'Close the Document
    oDoc.Close False
    Set oDoc = Nothing
    If bAppAlreadyOpen = False Then oApp.Quit
    Set oApp = Nothing
    Exit Sub

Error_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: PrintWordDoc" & vbCrLf & _
           "Error Description: " & Err.Description _
           , vbOKOnly + vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Sub


Function FileNameNoExt(strPath As String) As String
'https://sqlaccxl.wordpress.com/2013/03/06/vba-function-to-extract-file-name-withwithout-file-extension-or-path-only/
    Dim strTemp As String
    strTemp = Mid$(strPath, InStrRev(strPath, "\") + 1)
    FileNameNoExt = Left$(strTemp, InStrRev(strTemp, ".") - 1)
End Function

'The following function returns the filename with the extension from the file's full path:
Function FileNameWithExt(strPath As String) As String
    FileNameWithExt = Mid$(strPath, InStrRev(strPath, "\") + 1)
End Function

'the following function will get the path only (i.e. the folder) from the file's full path:
Function FILEPATH(strPath As String) As String
    FILEPATH = Left$(strPath, InStrRev(strPath, "\"))
End Function

Function FileExtension(strPath As String) As String
'Get the extension of the file name
'https://social.msdn.microsoft.com/Forums/en-US/d112ca5d-2304-4707-bade-b27869c9359f/vba-excel-getting-file-extension?forum=isvvba
'20190129
    FileExtension = Split(strPath, ".")(UBound(Split(strPath, ".")))
End Function
 
Last edited:

Users who are viewing this thread

Top Bottom