Is there a way to automatically attach a document to an email?

I am looking for a way to automatically attach a word document to an email that will be sent when triggered. Right now I have it set up on a button trigger for testing purposes. I have used the format that is in the inductive automation documents. I have looked into attachmentData and attachmentNames, but I am still learning so if those are used I am not sure how to use them effectively.

filePath = system.net.openFile('docx','C:\Test_doc.docx')
if filePath != None:
   fileName = filePath.split("\\")[-1]
   fileData = fpmi.file.readFileAsBytes(filePath)
   smtp = "server.company.local"
   sender = "sender@companyname.com"
   subject = "Test Email From Ignition"
   body = "This is a test email from ignition."
   recipients = ["myname@companyname.com"]
   system.net.sendEmail(smtp, sender, subject, body, 0, recipients, [fileName], [fileData])

If I need to use the other methods mentioned in the documents I can do that as well, as I also have other buttons setup with those as well.Preformatted text

In your script, you have a spurious attachmentData stuck between subject and body. Try taking that out.

1 Like

Ah, yes, thank you, I missed that editing that out before posting. When trying different things.

In the first line, “system.net.openFile” should be “system.file.openFile” ?

1 Like

It worked for me like below

I don’t use the system.net.openFile because I already have the filepath.
To read the file I use system.file.readFileAsBytes(filepath), not sure what library is needed to use the “fpmi.file.readFileAsBytes(filePath)”

if filePath != None:
   fileName = filePath.split("\\")[-1]
   fileData = system.file.readFileAsBytes(filePath)
   smtp = "server.company.local"
   sender = "sender@companyname.com"
   subject = "Test Email From Ignition"
   body = "This is a test email from ignition."
   recipients = ["myname@companyname.com"]
   system.net.sendEmail(smtp, sender, subject, body, 0, recipients, [fileName], [fileData])