INTRODUCTION
I wrote this backup script and post it here in order to help starters get under way without too much worry. It backs up your data and Zips it to an archive folder, whilst removing previous zip archive files older than a defined period.
It is designed for systems using the INTERNAL database or a MySQL database only. (It is NOT written for any other database (as I do not know the methods for those databases - but feel free to change accordingly to suit. However, a quick google for MSSQL equivalent of dumping the database suggests this: https://www.howtogeek.com/50295/backup- ... mand-line/ - this will be the direct replacement for the full "mysqldump" command as found in the ":4th"of BackupMail.bat below).
It is an 'easy start' script offering requiring just a review of a few tailored variables at the top of the scripts.
It works very well and does the following:
- • backs up the hmaildata directory
• backs up the database keeping it inline with the hmaildata files
• updates spamassassin definitions if Spamassassin for Windows is installed and in use
• backs up other important custom data directories you wish to include
• clears down emails from the TRASH folders (or any others you wish to include) - tailorable from Zero to X days old
• performs and reports checks on the service stop/restarts to ensure continuity of data
* The data+database+customer datadrive goes into a single date-stamped ZIP file with a linked log file (eg "Serverdata_2015-03-10-200000.zip" and "Backup_2015-03-10-200000.log").
* The cleardown script gives you a nice email informing you of what happened detailing the accounts, and the quantities relating to their accounts that have been processed. (Copy and save as emailclearup.vbs - dont forget to change your parameters at implementation.)
* The whole backup routine gives you a FULL run down of what happened and emails you at the end (with variable SUBJECT depending on success/failure) with red highlighting of failures
eg
ADDITIONAL PREREQUISITESSubject: !!! Backup completed WITH ERRORS. CHECK LOG FILE FOR DETAILS!!!
Hmailserver service shutdown: Ok
Spamassassin service shutdown: Ok
Spam Assassin Def Update: Failed
Spam Assassin Service startup: Ok
Hmailserver service startup: Ok
Zip: Ok
Email Cleardown Script: Ok
See attached log file below for details.
NOTE: The solution uses THREE EXTRA scripts/programs:-
a, You will see in the section called :GoEmail that I use a 3rd party program called BLAT.exe to send the email notifications out - this standalone program needs to be downloaded and installed to use the script. You can change the reference to whatever your choice of emailer program is (you might use a CDO script or an HMS emailing script you already have written) - just replicate the appropriate parameters in the :GoEmail section on the calling command line in the BackupMail.Bat script.
b, It also uses 7zip that is shipped with Hmailserver (in the Bin directory) to perform the compression - again you can use or change to suit as you wish. See notes below.
c, It also utilises Windows Server 'ROBOCOPY' for doing the data copy (mirror). This is standard on most MS Server editions of windows but can easily be obtained for other OS's if you dont already have it.
d, The EMAILCLEARUP.VBS script also needs to be saved (to the same scripts directory) for being called upon.
IMPLEMENTATION
1, Download and save the 2 scripts (BackupMail.Bat and Emailcleardown.vbs) and save them into a SINGLE holding 'script' folder from where they will be called.
2, Download and install BLAT.exe (http://www.blat.net/) as necessary
3, REVIEW AND MODIFY the various variables at the top of both scripts - BE CAREFUL TO GET THEM RIGHT. Also, take a careful read through the BAT script and fill out the extra sections (such as ":7th", ":8th" etc) to add additional copying or processing of other directories in to the script where required.
4, Call the BackupMail.bat daily (with Task Scheduler)
The basis of the backup works by initially taking a MIRROR copy of the current data folder, so the first run could take some time and you will need to be aware of this for disk space purposes ie, you will need another 100% space allocation of the current data on whatever drive you specify under the %BACKUPTEMPdir% variable. Subsequent runs, however, will be a lot quicker as only 'incremental' changes a replicated. On my system it backs up 10.5GB of data and zips it in about 20 minutes in total whist the mail service is only offline for only around 30 seconds. Its important to leave this temporary directory populated for this speed benefit.
NOTE:
There is one thing you should note: the Zip file is currently as a type ZIP compression and not the 7zip native '7z' compression. The reason for this is because it is A LOT quicker than 7Z BUT it is not so compact. To explain better, note that my total unzipped directory starts at 10.5GB but
as a ZIP:
- time to zip: 17 minutes
size: 7.17GB
- time to zip: 51 minutes
size: 6.4GB
Code: Select all
7za a -tzip "%BACKUPdir%\Serverdata_%inDate%" "%BACKUPTEMPdir%\*"
At least I hope you find it useful as a starting point. You can always add to or remove more or irrelevant sections to suit but it should be sufficient as it is (if you follow the instructions and tailor the variables accordingly) to get you going with the important data.
BackupMail.Bat
Code: Select all
rem #### CONFIG START ####
rem ******* FILL OUT VARIABLES BELOW ***************************
set emailRecipient=admin@yourdomain.com
set emailFrom="Backup Daemon <noreply@yourdomain.com>"
rem --- SET LOCATIONS (without trailing '\') ----
Set BACKUPdir=D:\MailserverBackups
Set BACKUPTEMPdir=D:\BackupTemp
set MAILDATAdir=D:\hMailServer\Data
set HMAILSERVERprogdir=C:\Program Files (x86)\hMailServer
set BLATdir=C:\pathto\blat324\full\blat.exe
rem Spamassassin installed and in use: enter "yes" or "no" (lowercase!). Also set program directory if 'yes'.
set SA_In_Use=yes
set SPAMASSASSINdir=C:\Program Files (x86)\JAM Software\SpamAssassin for Windows
rem enter "internal" or "mysql" (lowercase!) as the database type in use
set DBtype=internal
rem ** IF DBtype = 'internal' set the following variables
set InternalDATABASEdir=C:\Program Files (x86)\hMailServer\Database
rem ** IF DBtype = MySQL set the following variables
set MYSQLBINdir=C:\Program Files\MySQL\MySQL Server 5.5\bin
set MYSQLDBuser=root
set MYSQLDBpass=yoursqlpassword
set MYSQLDBport=3306
rem --- HOW MANY recent backup Zips do you want to retain? ----
set DAYSZIPTOKEEP=7
rem **** FILL OUT VARIABLES ABOVE *******************************
rem #### CONFIG END ####
Set SCRIPTdir=%~dp0
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set inDate=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2%-%ldt:~8,6%
set BackLog="%BACKUPdir%\Backup_%inDate%.log"
set emailer_log="%SCRIPTdir%\emailer.log"
set Failed=false
set FailedScript=Not performed
set FailedZip=Not performed
set FailedSAUpdate=Not performed
set FailedSAService=Not performed
set FailedDNSService=Not performed
set FailedHmailservice=Not performed
set outf="%SCRIPTdir%\body.html"
echo ^<table border='0'^> > %outf%
set colorfill=font color="red"
set fontBlack=!--
set noBold=!--
echo Backup Start: %date% %time% > %BackLog%
REM :: Perform backup to temporary directory
set section=1st
:1st
:maildata
echo %time% Stopping Hmailserver service...>> %BackLog%&net stop hmailserver >> %BackLog%
set FailedHmailservice=Ok
set bold=%noBold%&set fontcolor=%fontBlack%
if errorlevel 1 set Failed=true&set FailedHmailservice=Failed to stop. Backup of emails not performed!&set bold=b&set fontcolor=%colorfill%
echo %FailedHmailservice%! >> %BackLog%
echo ^<tr^>^<td^>^<%fontcolor%^>^<%bold%^>Hmailserver service shutdown:^</td^>^<td^>^<%fontcolor%^>^<%bold%^>%FailedHmailservice%^</td^>^</tr^> >>%outf%
:2nd
if not "%SA_In_Use%" == "yes" goto 3rd
echo %time% Stopping Spamassassin service...>> %BackLog%&net stop spamassassin >> %BackLog%
set FailedSAService=Ok
set bold=%noBold%&set fontcolor=%fontBlack%
if errorlevel 1 set Failed=true&set FailedSAService=Failed to stop&set bold=b&set fontcolor=%colorfill%
echo %FailedSAService%! >> %BackLog%
echo ^<tr^>^<td^>^<%fontcolor%^>^<%bold%^>Spamassassin service shutdown:^</td^>^<td^>^<%fontcolor%^>^<%bold%^>%FailedSAService%^</td^>^</tr^> >>%outf%
@rem Update Spamassassin before restarting service
if "%FailedSAService%" == "Failed to stop" goto 3rd
echo %time% Performing Spamassassin Update check...>> %BackLog%
set FailedSAUpdate=Ok
cd /D "%SPAMASSASSINdir%"
sa-update.exe -v --nogpg --channelfile UpdateChannels.txt >> %BackLog%
set bold=%noBold%&set fontcolor=%fontBlack%
if errorlevel 1 set Failed=true&set FailedSAUpdate=Failed&set bold=b&set fontcolor=%colorfill%
echo ^<tr^>^<td^>^<%fontcolor%^>^<%bold%^>Spam Assassin Def Update:^</td^>^<td^>^<%fontcolor%^>^<%bold%^>%FailedSAUpdate%^</td^>^</tr^> >>%outf%
:3rd
set section=3rd
if "%FailedHmailservice:~0,14%" == "Failed to stop" goto 5th
robocopy "%MAILDATAdir%" "%BACKUPTEMPdir%"\hMailData /mir /ndl /r:43200 /np /w:1 >> %BackLog%
goto ROBOerrorcheck
:4th
if "%DBtype%" == "mysql" (
erase /Q "%BACKUPTEMPdir%"\hMailData\*.mysql >> %BackLog%
"%MYSQLBINdir%"\mysqldump -u"%MYSQLDBuser%" -p"%MYSQLDBpass%" -q -A -l --add-drop-table -PMYSQLDBport >"%BACKUPTEMPdir%\hMailData\MYSQLDump_%inDate%.mysql"
) ELSE (
xcopy /f /I /Y "%HMAILSERVERprogdir%"\Bin\hmailserver.ini "%BACKUPTEMPdir%"\Bin\ >> %BackLog%
robocopy "%InternalDATABASEdir%" "%BACKUPTEMPdir%"\Database /mir /ndl /r:43200 /np /w:1 >> %BackLog%
goto ROBOerrorcheck
)
:5th
@rem Restart Spamassassin and Hmailserver services
if not "%FailedSAService%" == "Ok" goto 6th
echo %time% Starting Spamassassin service...>> %BackLog%&net start spamassassin >> %BackLog%
set bold=%noBold%&set fontcolor=%fontBlack%
if errorlevel 1 set Failed=true&set FailedSAService=Failed to restart&set bold=b&set fontcolor=%colorfill%
echo %FailedSAService%! >> %BackLog%
echo ^<tr^>^<td^>^<%fontcolor%^>^<%bold%^>Spam Assassin Service startup: ^</td^>^<td^>^<%fontcolor%^>^<%bold%^>%FailedSAService%^</td^>^</tr^> >>%outf%
:6th
if not "%FailedHmailservice%" == "Ok" set section=7th & goto 7th
echo %time% Starting Hmailserver service... >> %BackLog%&net start hmailserver >> %BackLog%
set bold=%noBold%&set fontcolor=%fontBlack%
if errorlevel 1 set Failed=true&set FailedHmailservice=Failed to restart&set bold=b&set fontcolor=%colorfill%
echo %FailedHmailservice%! Errorlevel=%errorlevel% >> %BackLog%
echo ^<tr^>^<td^>^<%fontcolor%^>^<%bold%^>Hmailserver service startup:^</td^>^<td^>^<%fontcolor%^>^<%bold%^>%FailedHmailservice%^</td^>^</tr^> >>%outf%
REM --- Use the following sections 7th to 9th as example of adding other Data directories in the backup (remove the REM's) ---
:7th
:Sagedata
rem robocopy "D:\SageAccountData" "%BACKUPTEMPdir%"\SageAccountData /mir /ndl /r:43200 /np /w:1 >> %BackLog%
rem goto ROBOerrorcheck
:8th
:Miscdata
rem robocopy "D:\Miscdata" "%BACKUPTEMPdir%"\Miscdata /mir /ndl /r:43200 /np /w:1 >> %BackLog%
rem goto ROBOerrorcheck
:9th
rem robocopy "D:\anotherdir" "%BACKUPTEMPdir%"\anotherdir /mir /ndl /r:43200 /np /w:1 >> %BackLog%
rem goto ROBOerrorcheck
REM --- End of Example sections ---
:10th
REM:: Clear down existing backup Zips over DAYSZIPTOKEEP
echo. & echo Clearing old archives
forfiles.exe /s /p "%BACKUPdir%" /m *.* /d -%DAYSZIPTOKEEP% /c "cmd /c echo Deleting over %DAYSZIPTOKEEP% days....@path & del /q @path" >> %BackLog%
REM :: Zip temporary directory and email log file
cd /D "%HMAILSERVERprogdir%"\Bin >> %BackLog%
echo %date% %time% 7Zip Creating archive %BACKUPdir%\Serverdata_%inDate%.zip >> %BackLog%
set FailedZip=Ok
7za a -tzip "%BACKUPdir%\Serverdata_%inDate%" "%BACKUPTEMPdir%\*"
set bold=%noBold%&set fontcolor=%fontBlack%
if errorlevel 1 set Failed=true&set FailedZip=Failed&set bold=b&set fontcolor=%colorfill%
echo ^<tr^>^<td^>^<%fontcolor%^>^<%bold%^>Zip:^</td^>^<td^>^<%fontcolor%^>^<%bold%^>%FailedZip%^</td^>^</tr^> >>%outf%
REM :: Empty the Trash folder
echo. >> %BackLog%
set FailedScript=Ok
:runcleardown
echo Email clear up started at %time% ************************************ >> %BackLog%
cscript "%SCRIPTdir%"\EmailClearup.vbs //nologo //T:600 >> %BackLog%
echo Email clear up finished at %time% (errorlevel: %errorlevel%) **********************>> %BackLog%
if "%FailedScript%" == "RERUN-Ok" goto skiprun
if errorlevel 1 set FailedScript=RERUN-Ok& echo RERUN being called......***************>> %BackLog% & goto runcleardown
:skiprun
set bold=%noBold%&set fontcolor=%fontBlack%
if errorlevel 1 set Failed=true&set FailedScript=Failed&set bold=b&set fontcolor=%colorfill%
echo ^<tr^>^<td^>^<%fontcolor%^>^<%bold%^>Email Cleardown Script: ^</td^>^<td^>^<%fontcolor%^>^<%bold%^>%FailedScript%^</td^>^</tr^> >>%outf%
:test
set result=%date% %time% Backup procedure FAILED!!! Zip: %FailedZip%, Script: %FailedScript%, SA Update: %FailedSAUpdate%, SA Service: %FailedSAService%, Hmailserver service: %FailedHmailservice%.
set resulttext="!!! Backup completed WITH ERRORS. CHECK LOG FILE FOR DETAILS!!!"
if not %Failed%==false goto Testend
:success
set result=%date% %time% Backup 7Zip Archive created - no errors encountered.
set resulttext="Backup completed. See attachment log file."
goto Testend
:ROBOerrorcheck
if errorlevel 16 echo ***FATAL ERROR*** >> %BackLog% & goto end
if errorlevel 15 echo OKCOPY + FAIL + MISMATCHES + XTRA >> %BackLog% & goto end
if errorlevel 14 echo FAIL + MISMATCHES + XTRA >> %BackLog% & goto end
if errorlevel 13 echo OKCOPY + FAIL + MISMATCHES >> %BackLog% & goto end
if errorlevel 12 echo FAIL + MISMATCHES>> %BackLog% & goto end
if errorlevel 11 echo OKCOPY + FAIL + XTRA >> %BackLog% & goto end
if errorlevel 10 echo FAIL + XTRA >> %BackLog% & goto end
if errorlevel 9 echo OKCOPY + FAIL >> %BackLog% & goto end
if errorlevel 8 echo FAIL >> %BackLog% & goto end
if errorlevel 7 echo OKCOPY + MISMATCHES + XTRA >> %BackLog% & goto end
if errorlevel 6 echo MISMATCHES + XTRA >> %BackLog% & goto end
if errorlevel 5 echo OKCOPY + MISMATCHES >> %BackLog% & goto end
if errorlevel 4 echo MISMATCHES >> %BackLog% & goto end
if errorlevel 3 echo OKCOPY + XTRA >> %BackLog% & goto end
if errorlevel 2 echo XTRA >> %BackLog% & goto end
if errorlevel 1 echo OKCOPY >> %BackLog% & goto end
if errorlevel 0 echo No Change >> %BackLog% & goto end
:end
if errorlevel 8 set Failed=true
if %section%==9th set section=10th
if %section%==8th set section=9th
if %section%==7th set section=8th
if %section%==6th set section=7th
if %section%==5th set section=6th
if %section%==4th set section=5th
if %section%==3rd set section=4th
if %section%==2nd set section=3rd
if %section%==1st set section=2nd
goto %section%
:Testend
if not %FailedZip%==Failed forfiles /p "%BACKUPdir%" /m Serverdata_%inDate%.zip /d +0 /c "cmd /c echo Created: @path @fsize" >> %BackLog%
echo ^<tr^>^<td^>^<br^>^</td^>^</tr^>^</table^>See attached log file below for details. >>%outf%
echo %result% >> %BackLog%
echo %time% %inDate% backup log. Emailing.... >> %emailer_log%
:GoEmail
net start | find "hMailServer" > nul
if not %errorlevel%==0 echo Hmailservice not running - email not possible >> %emailer_log%&goto eof
if "%FailedHmailservice%" == "Failed to restart" echo Hmailservice not running - email not possible >> %emailer_log%&goto eof
"%BLATdir%" %outf% -mailfrom %emailFrom% -to %emailRecipient% -subject %resulttext% -server localhost -attachi %BackLog% -log %emailer_log%
:eof
echo ********************************** >> %emailer_log%
del %outf%
:Finish
Code: Select all
' Routine empties the TRASH folders (Zero days retained) and is called by scheduler
' in the backup script
Option Explicit
' #### CONFIG START ####
Const DAYS_TO_KEEP_MESSAGES = "0" ' Days old to keep mails
Const MESSAGES_FOLDER = "Trash|Deleted*" ' Folder to delete from, case insensitive, subfolder delimiter needs to be as
' below (.) based on ur delimiter setting in hmailserver, multiple folders can
' be specified seprated by | (pipe) and can include asterix wilcard
' eg: "spam|trash|deleted*|inbox.sub*"
Const IMAP_DELIMITER = "." ' This needs to be same as what u used above for subfolders based on delimiter
' setting in hmailserver
Const HMSADMINUSER = "Administrator" ' Admin username
Const HMSADMINPWD = "secretpassword" ' Admin password
Const HMSSERVER = "127.0.0.1" ' hMailServer Server (DCOM)
Const FROM_EMAIL = "system@yourdomain.com" ' Replace this with the email address you want the report to come from
Const REPORT_TO_EMAIL = "admin@yourdomain.com"' Replace this with the email address you want the report to be sent to
' #### CONFIG END ####
' Objects
Dim oApp, oDomains, oDomain, oAccounts, oAccount, oMessages, oMessage
' Numeric
Dim AccountSize, NumMsgs, NumDeleted, iMessages, x, y, z, MessageID, DeleteCount, LoopCount
' Strings / arrays
Dim SearchFolders, FindFolders, FoundFolder, FolderList, aFolder, SpamFolder, SpamFolderAction, TotalMsgs
Dim Message, CreateGUIDval, OutputMsg, w, FolderArray, SplitCount, xFolder
' Flags
Dim Skipped, ReturnValue : ReturnValue = 0
' Date / time
Dim MessageDate
' On Error Resume Next
SearchFolders = Split(MESSAGES_FOLDER, "|")
Set oApp = CreateObject("hMailServer.Application", HMSSERVER)
Call oApp.Authenticate(HMSADMINUSER, HMSADMINPWD)
For x = 0 To oApp.Domains.Count - 1
Set oDomain = oApp.Domains.Item(x)
If oDomain.Active Then
For y = 0 To oDomain.Accounts.Count - 1
Set oAccount = oDomain.Accounts.Item(y)
OutputMsg = OutputMsg & "<tr><td colspan=" & Chr(34) & "5" & Chr(34) & "> </td></tr>" & vbCrLf
If oAccount.Active Then
Skipped = ""
For Each SpamFolder in SearchFolders
TotalMsgs = 0
AccountSize = 0
NumMsgs = 0
NumDeleted = 0
Set FindFolders = oAccount.IMAPFolders
FoundFolder = False
FolderList = ListFolders(FindFolders, 0, "")
aFolder = Split(Left(FolderList, Len(FolderList) - 1), "|")
For Each z in aFolder
If UCase(z)=UCase(Trim(SpamFolder)) Or _
(Right(trim(SpamFolder),1)="*" And UCase(left(z,len(trim(Spamfolder))-1)) = UCase(left(trim(SpamFolder),len(trim(SpamFolder))-1))) Then
FoundFolder = True
SpamFolderAction = z
Set oMessages = GetInsideFolders(oAccount.IMAPFolders, SpamFolderAction)
NumMsgs = oMessages.Count
TotalMsgs = TotalMsgs + NumMsgs
iMessages = 0
DeleteCount = 0
LoopCount = 0
Do While oMessages.Count > (LoopCount - DeleteCount)
Set oMessage = oMessages.Item(iMessages)
AccountSize = AccountSize + oMessage.Size
MessageDate = oMessage.InternalDate
If (MessageDate < CDate(Now - DAYS_TO_KEEP_MESSAGES)) Then
If CLng(oMessage.ID) > 0 Then
NumDeleted = NumDeleted + 1
DeleteCount = DeleteCount + 1
oMessages.DeleteByDBID(oMessage.ID)
Else
Skipped = " *"
ShowError("---> Delete failed <---")
End If
Else
iMessages = iMessages + 1
End If
If oMessages.Count = (NumMsgs - DeleteCount) Then
LoopCount = LoopCount + 1
Else
NumMsgs = oMessages.Count
iMessages = 0
DeleteCount = 0
LoopCount = 0
End If
Loop
End if
Next
If FoundFolder Then
WScript.Echo "Removed " & NumDeleted & " message(s) from " & SpamFolder & " folder in account " & oAccount.Address & vbCrLf
OutputMsg = OutputMsg & "<tr><td>" & oAccount.Address & "</td>"
OutputMsg = OutputMsg & "<td>" & SpamFolder & "</td>"
OutputMsg = OutputMsg & "<td align=" & Chr(34) & "right" & Chr(34) & ">" & FormatNumber(TotalMsgs, 0, True, False, True) & "</td>"
OutputMsg = OutputMsg & "<td align=" & Chr(34) & "right" & Chr(34) & ">" & FormatNumber(AccountSize, 0, True, False, True) & "K</td>"
OutputMsg = OutputMsg & "<td align=" & Chr(34) & "right" & Chr(34) & ">" & FormatNumber(NumDeleted, 0, True, False, True) & Skipped & "</td></tr>" & vbCrLf
Else
WScript.Echo SpamFolder & " folder Not Found in account " & oAccount.Address
End If
Next
End If
Next
End If
Next
OutputMsg = "<font face=" & Chr(34) & "Calibri" & Chr(34) & "><table border=" & Chr(34) & "1" & Chr(34) & "><tr><td><b>Email Account</b></td><td><b>Folder</b></td><td><b>Mail Count</b></td><td><b>Mail Size</b></td><td><b>Deleted</b></td></tr>" & vbCrLf & OutputMsg
OutputMsg = OutputMsg & "</table>" & vbCrLf
Set Message = CreateObject("hMailServer.Message", HMSSERVER)
Message.HeaderValue("Message-ID") = "<" & CreateGUID & ">"
Message.FromAddress = FROM_EMAIL
Message.From = "Email Clearup Daemon <"& FROM_EMAIL & ">"
Message.AddRecipient "System Administrator", REPORT_TO_EMAIL
Message.Subject = "Email Clearup deletion report"
Message.HTMLBody = OutputMsg
Message.Save
Wscript.Quit ReturnValue
Function ShowError(strMessage)
WScript.Echo strMessage
WScript.Echo Err.Number & " Srce: " & Err.Source & " Desc: " & Err.Description
ReturnValue = Err.Number
Err.Clear
End Function
Function ListFolders(obFolders, iRecursion, rootFolder)
iRecursion = iRecursion + 1
Dim sMessage
Dim i
For i = 0 To obFolders.Count -1
Dim obFolder
Set obFolder = obFolders.Item(i)
If iRecursion > 1 Then
FolderArray = Split(rootFolder, IMAP_DELIMITER)
SplitCount=0
for each xFolder in FolderArray
SplitCount=SplitCount+1
if SplitCount < iRecursion then
if SplitCount = 1 then
rootFolder = xFolder
else
rootFolder = rootFolder & IMAP_DELIMITER & xFolder
end if
else
if SplitCount = iRecursion then
Exit for
End if
end if
next
sMessage = sMessage & rootFolder & IMAP_DELIMITER & obFolder.Name & "|"
Else
sMessage = sMessage & obFolder.Name & "|"
End If
If iRecursion = 1 Then
rootfolder =obFolder.Name
Else
rootFolder = rootFolder & IMAP_DELIMITER & obFolder.Name
End If
sMessage = sMessage & ListFolders(obFolder.SubFolders, iRecursion, rootFolder )
Next
iRecursion = iRecursion -1
ListFolders = sMessage
End Function
Function GetInsideFolders(obFolders2, subFolders)
Dim iRecursion2
iRecursion2 = 1
Dim SeprateFodlers
SeprateFodlers = Split(subFolders, IMAP_DELIMITER)
For Each w in SeprateFodlers
If iRecursion2 = 1 Then
Set obFolders2 = obFolders2.ItemByName(w)
iRecursion2 = iRecursion2 + 1
Else
Set obFolders2 = obFolders2.SubFolders.ItemByName(w)
End If
Next
Set GetInsideFolders = obFolders2.Messages
End Function
Function CreateGUID()
' Generate a random string.
With CreateObject("hMailServer.Utilities", HMSSERVER)
CreateGUID = Mid(.GenerateGUID, 2, 36) & "@randommail"
End With
End Function
--- Using an External MySQL server ---
The script is designed for installations where the database is on the same server as Hmailserver. However, if you have a MySQL database on a separate external server then you will need to make a slight adjustment to the scripts (courtesy of Mattv8, here):
Get the "mysqldump.exe" command line utility
Visit https://dev.mysql.com/downloads/mysql/ and download the latest version of MySQL community server as a zip archive. Once the zip file has downloaded, extract it and browse to the bin folder. Copy the file "mysqldump.exe" to somewhere convenient on your server. Note the directory that you copy it to.
Changes to the script BackupMail.bat
Next, you will need to make the following adjustments to the BAT script:
- Specify the MYSQLBINdir to the directory you just copied "mysqldump.exe" to.
- Add a new variable called MYSQLDBhost. Point this new variable to the ip address or hostname of your MySQL server. I just added this to the MySQL database section, which should now look something like the following:
Code: Select all
rem ** IF DBtype = MySQL set the following variables. rem ** Make sure mysqldump.exe is in the script folder, or update line 37 of this script. set MYSQLBINdir=C:\Program Files (x86)\hMailServer\Backup set MYSQLDBuser=root set MYSQLDBpass=password set MYSQLDBhost=192.168.0.123 set MYSQLDBport=3306
- Edit section 4th to look like the following:
Code: Select all
:4th if "%DBtype%" == "mysql" ( erase /Q "%BACKUPTEMPdir%"\hMailData\*.mysql >> %BackLog% "%MYSQLBINdir%"\mysqldump.exe -h"%MYSQLDBhost%" -u"%MYSQLDBuser%" -p"%MYSQLDBpass%" -q -A -l --add-drop-table -PMYSQLDBport >"%BACKUPTEMPdir%\hMailData\MYSQLDump_%inDate%.mysql" ) ELSE ( xcopy /f /I /Y "%HMAILSERVERprogdir%"\Bin\hmailserver.ini "%BACKUPTEMPdir%"\Bin\ >> %BackLog% robocopy "%InternalDATABASEdir%" "%BACKUPTEMPdir%"\Database /mir /ndl /r:43200 /np /w:1 >> %BackLog% goto ROBOerrorcheck )
LOG FILES
Some people might choose to save disk space by also clearing down their Hmailserver LOGS directory; in doing so you can perhaps save over to 90% in disk space initially taken up by the logs). The following code identifies the current location of the LOGS, zips the log files to a .7z compressed file, and then deletes the logs.
If wish this functionality then add the following code in to the Batch file somewhere similar to section "8th" or "9th" (or in to a separate batch file of your choice):
Code: Select all
FOR /F "eol=; eol=[ tokens=1,2* delims==" %%i in ('findstr /b /l /i "Logfolder"= "%programfiles(x86)%\hMailServer\Bin\hmailserver.ini"') DO set Logpath=%%~j
"%programfiles(x86)%\hMailServer\Bin\7za" a -t7z "%Logpath%\Logs.7z" -uq0 "%Logpath%\hmailserver_????-*.log" -xr!*.7z
del "%Logpath%"\hmailserver_????-*.log