Search code examples
msbuildmsbuildcommunitytasks

Email MSBuild errors - only when there are errors


 msbuild MyProject.proj /fl /flp:v=detailed;logfile=mylog.txt
 msbuild MyProject.proj /t:ErrorEmail 

I have implemented this, and it works when there are errors. But it's also sending an email when there are no errors. How can I set up a condition if the file is empty, or there are 0 line count in the ReadLinesFromFile?

> <Target Name="ErrorEmail">    
>   <ReadLinesFromFile
>       File="mylog.txt"
>       Lines="_ErrorLines"
>       />
>   <MSBuild.Community.Tasks.Mail
>       SmtpServer="mailhost.amsa.com"
>       To="$(ErrorEmails)"
>       From="$(FromEmail)"
>       Subject="Build failure for $(SolutionName)" 
>       Body="Error details: @(ErrorFileContents, '%0D%0A')"
>       />
>  </Target>

Solution

  • Assuming ErrorFileContents is not empty in case of an error, you can iterate through its items to set a condition flag.

       <CreateProperty Value="true">
          <Output Condition="'%(ErrorFileContents.Identity)' != ''"
              TaskParameter="Value"
              PropertyName="SendMail" />
        </CreateProperty>
    
        <MSBuild.Community.Tasks.Mail Condition="'$(SendMail)' == true"
            SmtpServer="mailhost.amsa.com"
            To="$(ErrorEmails)"
            From="$(FromEmail)"
            Subject="Build failure for $(SolutionName)"
            Body="Error details: @(ErrorFileContents, '%0D%0A')"
           />