Sending attachments as an email from a form - NOT from local files - jakarta-mail

I have created a HTML email form which allows a user to enter To, subject, message, content and attachments however I cannot get the attachments to send.
I have researched online and came across many variations of this code:
messageBodyPart = new MimeBodyPart();
String filename = "/home/manisha/file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
But is there a way of sending attachments input into the form instead of adding the file path to a file in the code?
Thanks

First, the files need to be uploaded from the browser to the server using the html form. Depending on what you're using to manage the uploaded data, you can store the file data in memory or in files on the server. If you store it in memory, you can use a ByteArrayDataSource instead of FileDataSource in your code above.

Related

Discord JDA using a local image in an embed?

Is it possible to use a local image file as a thumbnail/image in an embedded message with Discord JDA?
For one of my commands i'm building an image programmatically and uploading it via the Imgur API before displaying it in an embedded message using the Imgur URL.
I know I can send the file to the channel directly but i'd like it to be contained within an embed that displays other relevant info.
Cheers
You can use attachment://filename.ext as described in the documentation for setImage.
For instance, if you have a file called cat-final-copy-final-LAST.png you can send it like this:
// the name locally is not cat.png but we can still call it cat.png when we send it with addFile
File file = new File("cat-final-copy-final-LAST.png");
EmbedBuilder embed = new EmbedBuilder();
// this URI "attachment://cat.png" references the attachment with the name "cat.png" that you pass in `addFile` below
embed.setImage("attachment://cat.png");
Then send it, with 5.X like this:
// this name does not have to be the same name the file has locally, it can be anything as long as the file extension is correct
channel.sendMessage(embed.build())
.addFiles(FileUpload.fromData(file, "cat.png"))
.queue();
Or with JDA 4.X:
// this name does not have to be the same name the file has locally, it can be anything as long as the file extension is correct
channel.sendMessage(embed.build())
.addFile(file, "cat.png")
.queue();

Include additional attachment blob to existing messages attachments in MailApp.sendEmail

I am using MailApp sendEmail in Google Apps Scripts to fetch an existing email, send it to another different address, with attachments, but also adding the message.getrawcontent() as additional attachment as txt file. I am not able to add element (i.e. attachment) to the blobsource[] array. Thereby, I am either able to send the txt file attachment of message.getrawcontent() or the original attachments, but not both.
I have creating creating an array of existing and new attachments but it does not work. I have creating creating an array such as
[messages[m].getAttachments(), blob]
but it does not work.
MailApp.sendEmail({to: email,subject: ThisMessageSubject,htmlBody: messages[m].getBody(),attachments: [messages[m].getAttachments(), blob],});
I am hoping to get both, the original messages[m] attachments as well as blob attachment as txt of messages[m].getrawcontent()

sending a .rtf file with javaMail

I am trying to get a file with the .rtf extension as an attachment with an email. I cannot seem to get it in my mailbox.
the code I currently use
try
{
Message msg = new MimeMessage(session);
msg.setFrom( ); // this is filled in but hidden for this question
msg.addRecipient();// this is filled in but hidden for this question
msg.setSubject("test email");
msg.setText("body test content");
msg.setSentDate(new Date());
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
FileDataSource source = new FileDataSource(receiveFile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.attachFile(backupFile);
messageBodyPart.setFileName("reportFile.rtf");
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
Transport.send(msg);
}
receiveFile is the rtf file in question that needs to be send as an attachement.
Do not bother wtih server settings and such. I have send emails using this code so that works all just fine :). and had success sending .txt or .doc files as well so I know my info is correct. just when I try to send it as reportFile.rtf the mail just does not arrive. and I have tried 2 systems both together (the datahandler + source path and the attachFile path) and both did not really give me what I wanted.
Is a rtf file as attachment possible using javaMail or am I looking in the wrong direction?
After looking at it more closely with my co-worker we figured out that the email I used as sender was interperted as a spam and thus dumped it in the spam folder. now in itself this is not a problem since it was fine for testing. However it seems that if you keep spamming with that address the mail server indeed blocks like a good percentage of the mails i was sending. So this made it hard to debug since it sometimes got through and sometimes did not. the issues has been resolved now.

java mail attachments getting corrupted

This is my code for attaching the files to the mail:
Multipart mp=new MimeMultipart("mixed");
BodyPart mbody=new MimeBodyPart();
mbody.setHeader("Content-Type", "text/html; charset=us-ascii");
mbody.setHeader("Content-Transfer-Encoding","7bit");
mbody.setContent(content2, "text/html");
mp.addBodyPart(mbody);
for(File file:f){
BodyPart mbody2=new MimeBodyPart();
DataSource ds=new FileDataSource(file.getAbsolutePath());
mbody2.setDataHandler(new DataHandler(ds));
mbody2.setFileName(ds.getName());
mbody2.setHeader("Content-Type", "multipart/mixed");
mbody2.setHeader("Content-Transfer-Encoding", "base64");
mp.addBodyPart(mbody2);
}
m.setContent(mp);
content2 is the html content I am embedding in the E-mail, and I am adding files from an arraylist f.
The problem here is that although the files get attached and I receive the E-mail fine, I am unable to open the attachments because the data is corrupt. This happens for all the files I've tried to attach like jpegs, pdfs, spreadsheets, word docs and txt files.
I read here: https://community.oracle.com/thread/1589120 that this could happen because JavaMail uses encoding that messes up the binary data of the file and adding mbody2.setHeader("Content-Transfer-Encoding", "base64"); should fix the problem but that doesn't work for me.
Any ideas on what could be wrong?
Thanks
Time for some debugging...
First, remove all of the setHeader calls; some of them are wrong and none of them should be necessary.
Next, determine if the problem is on the sending end or the receiving end. Try multiple mail readers to see if they all have problems with the attachments.
Try sending plain text attachments. Are they also corrupted?
Post the protocol trace showing what happens when you send a simple message with a simple attachment that fails, so we can see if the message is being constructed correctly.
What version of JavaMail are you using?
What mail reader are you using to view the attachments?

How can i extract attachments from salesforce?

I need to extract attatchments out of salesforce? I need to transfer some notes and attachments into another environmant. I am able to extract the notes but not sure how to go about extracting the attatchments
Thanks
Prady
This mostly depends on what tools/utilities you use to extract. The SOQL for Attachment sObject will always return one row at a time if Body field is included in the query. This is enforced to conserver resources and prevent overbearing SOQL scripts.
Approach #1, if queryMore is not available: Issue a SOQL without Body field to enumerate all attachments, then issue one SOQL per attachment ID to retrieve Body
Approach #2: Issue a SOQL to retrieve all needed attachments then loop using queryMore to get them one at a time.
Approach #3: If you can "freeze" the SF environment and just want to take snapshot of the system to pre-load a different one to be used going forward you can use "data exports". In setup menu, in data management there is an export data command, make sure you click "Include in export" to include all binary data. After due process it will give you a complete data backup you can crunch offline.
Btw, body is base64 encoded, you'll need to decode it to get the actual binary
Here is the solution I've used to get the attachment binary content from SalesForce. The example in their documentation points the following:
curl
https://na1.salesforce.com/services/data/v20.0/sobjects/Document/015D0000000NdJOIA0/body
-H "Authorization: Bearer token"
So there are a couple different elements here. The host (https://na1.salesforce.com) you should be able to get after the login process, this host is session based so it can always change. Second element is the rest of the URL, that you will get from the "body" field of the Attachment object. Third and last element is the Authorization header, which is composed by the string "Bearer ", plus the token that is given to you after you authenticate with the SF backend.
The response is the binary file, it is NOT in base64, just save it to a file and you are good to go.
Here is an example of how I did it in Objective C:
// How to get the correct host, since that is configured after the login.
NSURL * host = [[[[SFRestAPI sharedInstance] coordinator] credentials] instanceUrl];
// The field Body contains the partial URL to get the file content
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", [host absoluteString], {AttachmentObject}.body]];
// Creating the Authorization header. Important to add the "Bearer " before the token
NSString *authHeader = [NSString stringWithFormat:#"Bearer %#",[[[[SFRestAPI sharedInstance] coordinator] credentials] accessToken]];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
[urlRequest addValue:authHeader forHTTPHeaderField:#"Authorization"];
[urlRequest setHTTPMethod:#"GET"];
urlConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
Hope it helps.
You can use SOQl Query options, or if you are looking for some automation tool that will help you with quick export, then you can try AppExchange App Satrang Mass File Download - https://appexchange.salesforce.com/listingDetail?listingId=a0N3A00000EcsAOUAZ&tab=e
Disclaimer: I work at Satrang Technologies, the publisher of this Mass File Download AppExchange App.
In SalesForce attachment will be against an Object for e.g. Account object.
Steps to retrieve attachment (in Java)
Get the ID of the Object to which a file is attached. e.q. Account Object
String pid = Account__r().getId();
Execute a Query on Salesforce Object "Attachment" for the ID in Step 1
*String q = "Select Name, Body, ContentType from Attachment
where ParentId = '" + pid + "'";
QueryResult qr = connection.query(q);
SObject[] sarr = qr.getRecords();*
SObject so = sarr[0];
Typecast Salesforce Generic Object (SObject) to "Attachment" object
*Attachment att = (Attachment)so;*
Retrieve the Byte Array Stream from Body of Attachment, and do the operation needed on byte array.
*byte[] bName = att.getBody();
// Do your operation in byte array stream*

Resources