-1

I'm using Java's email class to send an email through our SMTP server. I want to add a feature where if a user resubmits their form, I email them an attachment with a copy of the old data and their new data they are submitting, so they can see the changes they are making. I don't have a problem with this flow, it's when I want to add them to my email I run into issues. Most of the solutions I've seen for adding attachments to a java email consist of attaching a system file, but these objects are generated at runtime, and I don't want to start adding files to the system just for this feature, so I wanted to know if I can add objects specifically as attachments.

user3334871
  • 1,251
  • 2
  • 14
  • 36

1 Answers1

0

If you were going to output the object to the console for debugging purposes, how would you do that? Would you .ToString() it, would you iterate over the properties and output them as individual strings?

Rather than think about the object as an object, think about how you want to show it to your users. If this involves a lot of rows with descriptors so they know what the data mean, then output it like that. If they are developers and expect to see it as JSON, output it formatted like that.

Most likely, you'll have to iterate over the object in some way to output it as strings in the body itself.

If you really want to add an attachment, you can create a temporary file (with a random name to prevent overwriting the file), send the email with the attachment, then delete the file.

I was going to say that there's probably a way to create a file in memory without saving it to disk that you can use as an attachment, but maybe there isn't in Java.

Create a File object in memory from a string in Java

computercarguy
  • 2,173
  • 1
  • 13
  • 27
  • We use Jackson mapping, so the object is mapped to a JSON format before being sent to our DB, so it would be a JSON structure being attached to the email. I'd like to avoid writing temp files to the system, I'm wondering if theres a way to stream it? – user3334871 Jul 25 '19 at 17:57
  • 1
    @user3334871, I looked for it, but in the 5 min I spent, I couldn't find an obvious or easy way. There's a possibility of using a byte stream in memory as a file, but it looked pretty complicated and I wasn't sure if it would work as an attachment. I thought adding that info would muddy up my answer to make it useless as an answer, so I didn't include it. – computercarguy Jul 25 '19 at 18:00