Function to send email returning errors when called

sp_send_dbmail is NOT a function - it is a stored procedure provided by Microsoft.

There is no reason to wrap the stored procedure as a function and in your example you are not actually calling the function correctly. A function is either a scalar or table function - so it has to be used as either a column or a table (e.g. SELECT dbo.Function(parameters) FROM sometable - or SELECT {somecolumns} FROM dbo.Function(parameters)).

You should also investigate how to use sp_send_dbmail fully - as everything you appear to be doing in these other procedures can be done just using sp_send_dbmail. For example, you can have sp_send_dbmail create the output file for you - as well as run the query to get the data - directly.

Again - you can pass the query, the query database, the flag to attach a file, the attachment filename, etc...