How to send mail with attachment in GWT? - java

I would like to know if there is a way to send an email with attachment file with GWT.
I managed to send a simple email without attachment, but I am having a problem when I try to add a file.
The problem is that "FileUpload" don't give the fullpath of the file
it seems for safety reasons it is impossible to retrieve the full path of the file from the client.
Is there another way keeping the logical server in gwt client?
My code
Client side:
FileUpload upload = new FileUpload();
// cannot retrieve the full path
String fileAttachment = upload.getName();
Server side:
public void sendMail(String sender, String[] recipients, String subject, String message, String fileAttachment) {
try {
...(init)
// Part two is attachment
messageBodyPart = new MimeBodyPart();
// => fileAttachment need full path
DataSource source =
new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(multipart);
// Send
Transport.send(msg);
}
Thanks for your help

You have to actually upload the file to the server.
The easiest way in GWT is to put your FileUpload (and all your form input widgets) in a FormPanel; it has the drawback of making error handling (and response handling from the server) more difficult though.
An alternative, in recent browsers, is to get the File object (not a java.io.File, a JS object) out of the FileUpload and upload it using XMLHttpRequest (possibly coupled with FormData to also send the other form values). In GWT, that means using JSNI (it might be possible to use the Elemental library too), and really know the innards of what you're doing.
In any case, you won't be able to use GWT-RPC to talk to your server and send the file at the same time.

Related

add footer/signature to mail in Java

In one of my Java applications I have to forward e-mails. So, I get e-mails (plain text or multipart) with any content (maybe also attachments). I edit their subject, from- and to-header and send them via SMTP.
I already implemented this using Apache James Mime4j and Apache Commons Net but now I also have to append a footer/signature to the content of each e-mail.
Can I achieve this with Mime4j too? Would be great! How? If not: is there another way?
EDIT: Details after Wolfgang Fahl's comment:
Maybe I'm using the library the wrong way, but I am parsing the message as follows:
MessageBuilder messageBuilder = new DefaultMessageBuilder();
InputStream in = ...
Message m = messageBuilder.parseMessage(in);
Now I have an instance of Message and I can set it's subject, sender, etc. But Message does not provide a method setText() or something like that. Ok, there is getBody() but then I don't know how to manipulate the Body.

Upload files using GWT Request Factory

Is it possible to upload file via request factory? Simple example will be really helpful.
Actually you can!, I have an application doing it already.
You need browsers supporting the FileApi (modern browsers do)
You have to write some jsni code to read the file content into a base64 string.
You will receive (asynchronously) a string which you can assign to any Bean attribute in your app and send it via RF, RPC, etc.
Here you have a copy/paste of the most significant code i use:
public final native void readAsDataURL(MyClass that, FileUpload input) /*-{
var files = input.#com.google.gwt.user.client.ui.FileUpload::getElement()().files;
var reader = new FileReader();
reader.onload = function (evt) {
that.#...MyClass::done(Ljava/lang/String;)(evt.target.result);
}
reader.readAsDataURL(files[0]);
}-*/;
It would be a comming-soon feature on my gwtupload library.
No.
You need to create a separate file upload servlet. See Basic File upload in GWT.
IMO RPC or Request Factory sense is XMLHttpRequest, which does not allow you encode and send local files to a server.
You need to write your own servlet and a GWT FormPanel .
complete example here with servlet and its mapping

Is it possible to build Apache HtmlEmail from string representation?

I'm building a ImageHtmlEmail in order to download and embed all the images from given HTML into a multipart email. I need to store that email for sending later.
Problem is, I can get the resulting email text and content-type, but I see no means to construct an ImageHtmlEmail back from a text and a content-type. Is it possible at all? Or should I go with raw javax.mail for actual sending?
I was able to create javax.mail.internet.MimeMessage out of String representation of an email (ASCII dump as one one get on downloading original email from gmail). However not been very successful in constructing Email subclasses like HtmlEmail from it yet.
MimeMessage mimeMessage = MimeMessageUtils.createMimeMessage(Session.getDefaultInstance(new Properties()), new ByteArrayInputStream(oneEmail.toString().getBytes()));
It does give me most of the things I can think of as useful using its getter methods.
Not sure what you mean with "building HtmlEmail from string", but constructing an ImageHtmlMail should be fairly easy, see the sample at http://commons.apache.org/email/userguide.html, all you need to provide is some html-text via setHtmlMsg()
import org.apache.commons.mail.HtmlEmail;
...
// load your HTML email template
String htmlEmailTemplate = ....
// define you base URL to resolve relative resource locations
URL url = new URL("http://www.apache.org");
// create the email message
HtmlEmail email = new ImageHtmlEmail();
email.setDataSourceResolver(new DataSourceResolverImpl(url));
email.setHostName("mail.myserver.com");
email.addTo("jdoe#somewhere.org", "John Doe");
email.setFrom("me#apache.org", "Me");
email.setSubject("Test email with inline image");
// set the html message
email.setHtmlMsg(htmlEmailTemplate);
// set the alternative message
email.setTextMsg("Your email client does not support HTML messages");
// send the email
email.send();

parse attachment from multipart mail content string in java

I'm testing an application sending a mail with attachment in a integration environment. For this i'm setting up a fake smtp mail server (http://quintanasoft.com/dumbster/) and configure my application to use it. At the end of my test i want to check if my application has sent the email via my fake mail server and also want to know, if the content (at least the attached file) is exactly that i'm expecting.
Dumpster is wrapping these mails into its own objects just containing header key-value pairs and the body as plain text. My question is how i can easily part the mail body to get and evaluate the attached file content from it.
Attach a file that you are certain of the mime-types in javamail. Sending the email over smtp allows us to make use of the fact that there is a string of data inside the body of the email before the bytes of the file. The bytes of the file are base64 and get included in the main chunk of the characters of the email.
private static final String YOUR_ATTACMETN_DATA = "Content-Type: image/jpeg; name=Invoice.jpgContent-Transfer-Encoding: base64Content-Disposition: attachment; filename=image.jpg";
#Before
public final void setup() throws UserException{
server = SimpleSmtpServer.start();
}
#After
public final void tearDown(){
server.stop();
}
#Test
public void test_that_attachment_has_been_recieved() throws IOException, MessagingException {
email = getMessage();
YourEmailSendingClass.sendEmail(email);
Iterator<SmtpMessage> it = server.getReceivedEmail();
SmtpMessage recievedMessage = (SmtpMessage)it.next();
assertTrue(recievedMessage.getBody.contains(YOUR_ATTACHMENT_DATA)));
}
Here is another is a page of someone who did something similar to this in greater detail.
http://www.lordofthejars.com/2012/04/why-does-rain-fall-from-above-why-do.html
As a place to start (not sure if there are easier ways to do it), consider using the JavaMail API. Try to grab the whole message (including headers) -- probably with SmtpMessage.toString(), wrap it in some new ByteArrayInputStream(smtpMessage.toString().getBytes()), and pass it to a javax.mail.internet.MimeMessage.
(NOTE: I'm not that familiar with the MIME standard and I don't know if you should use the getBytes(Charset) overload here).

Send an E-Mail with attachment using JAVA Mail API without storing in local machine

I have report in my jsp page and I am writing that report in PDF Format.
And I want to send the PDF as E-Mail with attachment, but I don't want store the file in local machine or server, but i want to send an email with the attachment.
If you use Spring's JavaMail API, you can do this sort of thing fairly easily (or at least, as easily as the JavaMail API allows, which isn't much). So you could write something like this:
JavaMailSenderImpl mailSender = ... instantiate and configure JavaMailSenderImpl here
final byte[] data = .... this holds my PDF data
mailSender.send(new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
// set from, to, subject using helper
helper.addAttachment("my.pdf", new ByteArrayResource(data));
}
});
The attachment data can be any of Spring's Resource abstractions, ByteArrayResource is just one of them.
Note that this part of the Spring API stands on its own, it does not require (but does benefit from) the Spring container.
Since JavaMail 1.4 - mail.jar - contains javax.mail.util.ByteArrayDataSource
https://javamail.java.net/nonav/docs/api/javax/mail/util/ByteArrayDataSource.html
( https://javamail.java.net/nonav/docs/api/ )
http://www.oracle.com/technetwork/java/javamail/index-138643.html - download location
regards
You have to write your own implementation of javax.activation.DataSource to read the attachment data from an memory instead of using one of the included implementations (to read from a file, a URL, etc.). If you have the PDF report in a byte array, you can implement a DataSource which returns the byte array wrapped in a ByteArrayOutputStream.

Categories

Resources