%REM
	Agent schForwardDeadMail
	Created Jan 1, 2012 by Tripp W Black/Mindwatering
	Description: Forwards dead mail to recipient
%END REM
Option Public
Option Declare

Sub Initialize
	Dim s As New NotesSession
	Dim db As NotesDatabase				' current db
	Dim sendtonm As String				' send to nm
	Dim mDb As NotesDatabase			' mail.box db
	Dim mV As NotesView					' mail.box Mail view
	Dim mDoc As NotesDocument			' mail in mail.box view mV
	Dim mNDoc As NotesDocument			' next doc after mDoc in mV
	Dim fsuccess As Integer				' forward flag success
	
	' ********************* Customize Next Line *********************
	sendtonm = "nouser@mindwatering.com"
	' ***************************************************************
	
	On Error GoTo SErrorHandler
	
	Set db = s.Currentdatabase
	Set mDb = s.Getdatabase(db.Server, "mail.box", False)
	If (mDb Is Nothing) Then
		' quit
		Print "No mail.box on server: " & db.Server & ". Aborted."
		Exit Sub
	End If
	If Not (mDb.IsOpen) Then
		Call mDb.Open(db.Server, "mail.box")
		If Not (mDb.IsOpen) Then
			' give up
			Print "No mail.box on server: " & db.Server & ". Aborted."
			Exit Sub
		End If
	End If
	' target db is open, get documents
	Set mV = mDb.GetView("Mail")
	If (mV Is Nothing) Then
		' give up
		Print "No Mail view in mail.box. Aborted."
		Exit Sub
	End If
	Set mDoc = mV.GetFirstDocument()
	While Not (mDoc Is Nothing)
		' get next doc
		Set mNDoc = mV.Getnextdocument(mDoc)
		' forward
		fsuccess = ForwardDeadmemo(db, mDoc, sendtonm)
		' delete doc
		If (fsuccess=1) Then
			Call mDoc.Remove(True)
		End If
		' loop
		Set mDoc = mNDoc
	Wend
	Print "Done."

	Exit Sub

		
		
SErrorHandler:
	Print "(Initialize) Unexpected error: " & CStr(Err) & " " & Error$ & ", line: " & CStr(Erl) & "."
	Exit Sub
End Sub

%REM
	Function ForwardDeadMemo
	Description: Forwards dead mail.box memo to name passed
%END REM
Function ForwardDeadMemo(db As NotesDatabase, mDoc As NotesDocument, sendtonm As String) As Integer
	Dim nDoc As NotesDocument			' new memo
	Dim nbody As NotesRichTextItem		' body field
	Dim nsuccess As Variant				' success for forward render

	On Error GoTo FErrorHandler
	
	Set nDoc = db.CreateDocument()
	nDoc.SaveMessageOnSend = False
	Call nDoc.ReplaceItemValue("Form", "Memo")
	Call nDoc.ReplaceItemValue("ReplyTo", "System Agent - Do Not Reply")
	Call nDoc.ReplaceItemValue("Subject", "Fwd: " & mDoc.Subject(0) )
	Call nDoc.Replaceitemvalue("SendTo", sendtonm)
	Set nBody = New NotesRichTextItem( nDoc, "Body" )
	nsuccess = mDoc.RenderToRTItem( nBody )
	If (nsuccess) Then
		' send memo
		Call nDoc.Send(False, sendtonm)
	Else
		Set nDoc = Nothing
		ForwardDeadMemo = 0
		Exit function
	End If
		
	' return success
	ForwardDeadMemo = 1
FExit:
	Exit Function
FErrorHandler:
	Print "(ForwardDeadMemo) Unexpected error: " & CStr(Err) & " " & Error$ & ", line: " & CStr(Erl) & "."
	ForwardDeadMemo = 0
	Resume FExit
End Function