Search code examples
vbabatch-fileoutlook

Why is a line added to .Body when creating mail?


I use an Outlook rule to run a batch file in Windows that takes as input the Subject and the Body of the email (this means two arguments).

If I run the line directly as C:\Users\me\Desktop\firstplink.bat "subjectPartA subjectPartB" "bodyA bodyB", it does not add a line.

There are two arguments, which are in quotes. I have A and B so there are at least two words in the subject and in the body.

My code adds a line which is messing up the batch file.

Sub firstplink(item As Outlook.MailItem)
    strSubject = item.Subject
    MsgBox strSubject
    strBody = item.Body
    MsgBox strBody
    strProgramName = "C:\Users\me\Desktop\firstplink.bat"
    strAll = strSubject & " " & strBody
    all = """" & strProgramName & """ """ & strSubject & """ """ & strBody & """"
    MsgBox all
    Call Shell("""" & strProgramName & """ """ & strSubject & """ """ & strBody & """")
End Sub

Sub TestScript()
    Dim testMail As MailItem
    Set testMail = Application.CreateItem(olMailItem)
    testMail.Subject = "Test subject"
    testMail.Body = "bcTest bbody bb cxcvaa"
    Project1.Module1.firstplink testMail
End Sub

Solution

  • It appears that the VBA overhead on an Outlook.MailItem appends a vbCRLF to the Item.Body if it does not have one. Evidenced by this code

    Option Explicit
    
    Sub firstplink(item As Outlook.MailItem)
        Dim strSubject As String, strBody As String, strAll As String, strProgramName As String
        Dim all As String
        strSubject = item.Subject
        MsgBox strSubject
        Debug.Print Asc(Right(item.Body, 1))
        Debug.Print Asc(Right(item.Body, 2))
        strBody = item.Body
        MsgBox strBody
        strProgramName = "C:\Users\me\Desktop\firstplink.bat"
        strAll = strSubject & " " & strBody
        all = """" & strProgramName & """ """ & strSubject & """ """ & strBody & """"
        MsgBox all
        Call Shell("""" & strProgramName & """ """ & strSubject & """ """ & strBody & """")
    End Sub
    
    Sub TestScript()
        Dim testMail As MailItem
        Set testMail = Application.CreateItem(olMailItem)
        testMail.Subject = "Test subject"
        testMail.Body = "bcTest bbody bb cxcvaa"
        Project1.Module1.firstplink testMail
    End Sub
    

    The Immediate window reports 10 then 13 on the two Debug.Print's. If a vbCrLF is manually added (e.g. testMail.Body = "bcTest bbody bb cxcvaa" & vbCrLf) then a second vbCrLf is not added.

    This must have to do with a vbCrLf being expected to terminate the item.body and the overhead adds one if it does not exist to avoid a crash.