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).
Related
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.
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.
i have been trying to send SOAP attachment using Camel+SpringWS.
Following is code inside my RouteBuilder class, endpoint is working properly i have already got empty SOAP response :
from("spring-ws:rootqname:{http://www.lala.org/Bean}GetBookRequest?endpointMapping=#endpointMapping").process(new Processor() {
public void process(Exchange arg0) throws Exception {
//SpringWebserviceMessage msg = (SpringWebserviceMessage) arg0.getIn(); // --> SpringWebserviceMessage instance
arg0.getOut().addAttachment("test",new DataHandler(new FileDataSource("c:/CompanyLogo.jpg")));
}
});
I have also tried adding attachment through SpringWebserviceMessage, but it doesn't make any effect.
Is anyone know how to add SOAP Attachment with Camel+SpringWS?
I'm not familiair with Camel but I do remember a case where I had to place a SOAP attachment in the message with spring-ws as well. The trick for me was to use a SaajSoapMessage.
Below is a snippet on how to attach a file using spring-ws in java:
JAXBElement<ShowCandidateType> responseElement = (JAXBElement<ShowCandidateType>) kandidaatServiceTemplate.marshalSendAndReceive(
objectFactory.createProcessCandidate(processCandidate),
new WebServiceMessageCallback() {
public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
SaajSoapMessage saajMessage = (SaajSoapMessage) message;
//Use the file name as the contentId
saajMessage.addAttachment(file.getName(), file);
}
}
);
The key was implementing the doWithMessage and casting the WebServiceMessage to a SaajSoapMessage.
The Camel component for Spring-WS doesn't contains any attachment / header support that was officially released.
However, the latest snapshot of camel-spring-ws contains the patch that address this issue.
Look here: https://issues.apache.org/jira/browse/CAMEL-5724
Here is current doc of the proposed functionality
The header and attachment propagation
The endpoint will use so called "hook" the MessageFilter (default implementation is provided by BasicMessageFilter) to propagate the exchange headers and attachments into WebSdrviceMessage response.
Now you can use
exchange.getOut().getHeaders().put("myCustom","myHeaderValue")
exchange.getIn().addAttachment("myAttachment", new DataHandler(...))
Note: If the exchange header in the pipeline contains text, it generates Qname(key)=value attribute in the soap header.
Recommended is to create a QName class directly and put into any key into header.
Don't know how your webservice expects the attachment. I had a requirement to send attachment using Camel + Soap. If you plan to use '#mtom', you need to add a binary message part and then you need to add the attachment, with the reference to the binary part.
Or else, if your webservice is using base64 encoded attachments. You simply need to set your file contents, base64 encoded to the attachment field name in message.
If you can share the wsdl, I will be able to help you better.
i want to create an intranet mailing system using java.so suggest me which API and what classes to use.
Without doubts use Apache Commons Email - it's an industry standard.
Commons Email aims to provide a API for sending email. It is built on top of the Java Mail API, which it aims to simplify.
Some of the mail classes that are provided are as follows:
SimpleEmail - This class is used to send basic text based emails.
MultiPartEmail - This class is used to send multipart messages. This allows a text message with attachments either inline or attached.
HtmlEmail - This class is used to send HTML formatted emails. It has all of the capabilities as MultiPartEmail allowing attachments to be easily added. It also supports embedded images.
EmailAttachment - This is a simple container class to allow for easy handling of attachments. It is for use with instances of MultiPartEmail and HtmlEmail.
Use the JavaMail API
Take a look at http://java.sun.com/products/javamail/
Try this library: http://github.com/masukomi/aspirin
It can actually send email (some kind of embedded MTA):
public class Main {
public static void main(String[] args) throws MessagingException {
MailQue que = new MailQue();
MimeMessage mes = SimpleMimeMessageGenerator.getNewMimeMessage();
mes.setText("test body");
mes.setSubject("test subject");
mes.setFrom(new InternetAddress("my#local.com"));
mes.setRecipients(Message.RecipientType.TO, "foo#bar.com");
que.queMail(mes);
}
}
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.