'How to get email body text and attachments using mimemessage class in java
In my SMTP server code, I have a MimeMessage instance that I want to use for extracting the incoming mailbody(mail text) and mail attachments. To do this, I use the below implementation on client and server sides. However, I am only able to retrieve mail attachments. The code somehow detects CustomerEngineer.ahmet thing two times and none of them contains the mail body which is : "This is a message body". I can retrieve the image though.
In my java mail client, I created a mail with the following schema:
try {
// Create a default MimeMessage object
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
// Set Subject
message.setSubject("Hi JAXenter");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is a message body");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
DataSource source = new FileDataSource(new File(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\CustomerEngineer.png")));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("CustomerEngineer.ahmet");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
On my server side I use the following logic:
MimeMessage message = new MimeMessage(session, data);
public void seperateBodyAndAttachments(MimeMessage message) throws MessagingException, IOException {
String mimeType = message.getContentType();
Date dt = new Date();
if (message.isMimeType("text/*")) {
System.out.println("this containst a text file");
} else if (message.isMimeType("multipart/*")) {
Multipart mp = (Multipart) message.getContent();
int idx = 0;
int count = mp.getCount();
for (int i = 0; i < count; i++) {
BodyPart part = mp.getBodyPart(i);
String name = part.getDataHandler().getName();
if (part.isMimeType("text/*")) {
if (name == null) {
name = "text-" + (++idx) + ".txt";
}
System.out.println(name);
} else {
if (name == null) {
name = "attachment-" + (++idx);
}
FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir").concat("\\src\\main\\resources\\DevEnvironmentConfigFile\\" + name));
BufferedOutputStream bos = new BufferedOutputStream(fos);
part.getDataHandler().writeTo(bos);
bos.close();
}
}
} else if (message.isMimeType("message/rfc822")) {
// Not implemented
} else {
Object o = message.getContent();
if (o instanceof String) {
FileWriter fw = new FileWriter(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\downloads\\" + "text.txt"));
BufferedWriter bw = new BufferedWriter(fw);
bw.write((String)o);
bw.close();
} else if (o instanceof InputStream) {
FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\downloads\\" +"message.dat"));
BufferedOutputStream bos = new BufferedOutputStream(fos);
message.getDataHandler().writeTo(bos);
bos.close();
} else {
FileWriter fw = new FileWriter(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\downloads\\" +"unknown.txt"));
BufferedWriter bw = new BufferedWriter(fw);
bw.write((String)o);
bw.close();
}
}
}
Solution 1:[1]
In my case I needed to extract a MimeBodyPart from a MimeMessage. It was trickier than I thought but I ended up robbing these 2 methods from BouncyCastle
/**
* extract an appropriate body part from the passed in MimeMessage
*/
protected MimeBodyPart makeContentBodyPart(
MimeMessage message)
throws SMIMEException
{
MimeBodyPart content = new MimeBodyPart();
//
// add the headers to the body part.
//
try
{
message.removeHeader("Message-Id");
message.removeHeader("Mime-Version");
// JavaMail has a habit of reparsing some content types, if the bodypart is
// a multipart it might be signed, we rebuild the body part using the raw input stream for the message.
try
{
if (message.getContent() instanceof Multipart)
{
content.setContent(message.getRawInputStream(), message.getContentType());
extractHeaders(content, message);
return content;
}
}
catch (MessagingException e)
{
// fall back to usual method below
}
content.setContent(message.getContent(), message.getContentType());
content.setDataHandler(message.getDataHandler());
extractHeaders(content, message);
}
catch (MessagingException e)
{
throw new SMIMEException("exception saving message state.", e);
}
catch (IOException e)
{
throw new SMIMEException("exception getting message content.", e);
}
return content;
}
private void extractHeaders(MimeBodyPart content, MimeMessage message)
throws MessagingException
{
Enumeration e = message.getAllHeaders();
while (e.hasMoreElements())
{
Header hdr = (Header)e.nextElement();
content.addHeader(hdr.getName(), hdr.getValue());
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | georgiecasey |
