JavaMail attachment and body issue - java

I am using below code to attach a pdf file to mail (JAVAMAIL). this postion works perfectly and adds attachment to my mail but this mail does not have any body.
Multipart multipart = new MimeMultipart();
msg.setContent(multipart);
DataSource source = new FileDataSource(pdf);
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(pdf.getName().toString());
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
when i add below lines to my code it removes attachment and send me mail containing the text only.
msg.setText(body);
please help me to add both attachment and test body to my mail.

The problem is that if you want to send a message with attachments, then you need to have a part for your message, and a part for your attachment.
By calling setText in the message, you are throwing away the multipart you set earlier.
Your message needs to have an hierarchy that looks like this (more nesting is necessary if you want to have a plain text and html message):
MimeMessage
+- MimeMultiPart
+- MimeBodyPart (message)
+- MimeBodyPart (attachment)
For example
MimeMessage message = new MimeMessage(session);
MimeMultiPart multiPart = new MimeMultiPart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
multiPart.addBodyPart(messageBodyPart);
MimeBodyPart attachment = new MimeBodyPart();
attachment.setDataHandler(new DataHandler(source));
attachment.setDisposition(Part.ATTACHMENT);
attachment.setFileName(pdf.getName().toString());
multipart.addBodyPart(attachment);
message.setContent(multiPart);

I have added below lines to make it work.
Multipart multipart = new MimeMultipart();
msg.setContent(multipart);
DataSource source = new FileDataSource(pdf);
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(pdf.getName().toString());
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(body, "text/html");
multipart.addBodyPart(htmlPart);

Related

Inline image shown as attachment : JavaMail

I am trying to send an email with an inline image, but the image is getting send as an attachment instead of inline.
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
String filename = "logo.jpeg";
mimeMessage.setFrom(new InternetAddress("Bridge"));
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
mimeMessage.setSubject(subject);
MimeMultipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(content, "text/html");
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource fds = new ByteArrayDataSource(IOUtils.toByteArray(resourceFile.getInputStream()), MediaType.IMAGE_JPEG_VALUE);
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
messageBodyPart.setFileName(filename);
messageBodyPart.setHeader("Content-ID", "<logoimg>");
messageBodyPart.setHeader("Content-Type", MediaType.IMAGE_JPEG_VALUE);
multipart.addBodyPart(messageBodyPart);
mimeMessage.setContent(multipart);
mimeMessage.saveChanges();
javaMailSender.send(mimeMessage);
} catch (MailException | MessagingException | IOException e) {
log.warn("Email could not be sent to user '{}'", to, e);
}
And here is my HTML code for the image:
<img width="100" height="50" src="|cid:logoimg|" alt="phoenixlogo"/>
I have tried all the multipart types: "mixed", "relative", "alternative" but couldn't get it to work.
Here is image for same:
You don't want an inline image, you want an html body that references an attached image. For that you need a multipart/related message. See the JavaMail FAQ.
You need to add a separate MimeBodyPart: For Example
BodyPart imgPart = new MimeBodyPart();
DataSource ds = new FileDataSource("D:/image.jpg");
imgPart.setDataHandler(new DataHandler(ds));
imgPart.setHeader("Content-ID", "<the-img-1>");
multipart.addBodyPart(imgPart);
Then in the html you refer to the Image as:
<br>" + "<img src=\"cid:the-img-1\"/><br/>

Attach a MimeMessage to another MimeMessage

I have a MimeMessage A and would like to add another MimeMessage B as an attachment.
My (not working) attempt:
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(base64mimeMessage, "message/rfc822");
mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");
multipart.addBodyPart(mimeBodyPart);
Which causes an java.io.IOException: unsupported object at com.sun.mail.handlers.message_rfc822.writeTo later when i try to sign or encrypt the result.
Maybe it is helpful for somebody else, so here is a working solution
MimeBodyPart mimeBodyPart = new MimeBodyPart();
DataSource dataSource = new ByteArrayDataSource(Base64.decode(itemAttachment.getMimeContent(), Base64.DEFAULT), "message/rfc822");
mimeBodyPart.setDataHandler(new DataHandler(dataSource));
multipart.addBodyPart(mimeBodyPart);
Session session = Session.getInstance(new Properties());
MimeMessage mimeMessageToAttach = new MimeMessage(session);
MimeBodyPart attachment = new MimeBodyPart();
String contentType = "message/rfc822; name=mymail.eml";
attachment.setContent(mimeMessageToAttach, contentType);
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);

Unable to send html content with attachment using java mail api

i want to send to send the html content along with an attachment. So how can it be sent in same mail ?
Could someone guide me. Thanks
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.CC,new InternetAddress("username#abc.com"));
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(data, "text/html");
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "Data.xlsx";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
message.setSubject("FOS Report");
message.setContent(multipart);
//send the message
Transport.send(message);
System.out.println("message sent successfully...");
}
catch (MessagingException e) {
e.printStackTrace();}
When you have two different types of contents, (binary and HTML in your case), you have to use Multipart for correct rendition.
You can learn about Multipart here: http://docs.oracle.com/javaee/6/api/javax/mail/Multipart.html
On how to work with JavaMail with Multipart, a very nice tutorial here:
https://www.programcreek.com/java-api-examples/javax.mail.Multipart
Please comment/ inbox if you require further assistance.

Not able to send a zip file through javamail

I am trying to send an attachment containing a zip file through javamail. However, while sending it throws an exception as
com.sun.mail.smtp.SMTPSendFailedException: 552-5.7.0 This message was blocked because its content presents a potential 552-5.7.0 security issue.
I added MIME content type as application/zip but facing
javax.mail.MessagingException: IOException while sending message;
nested exception is:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type
application/zip at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1167)
Below is my code snippet:
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "application/zip");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
File srcFile = new File(System.getProperty("user.dir")+ "/Reports/");
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(srcFile.getPath()+"/Report.zip");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("Report.zip");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
When I remove the .zip extension it works fine but not with .zip.
Your code is adding the attachment twice, which I'm sure is not what you want. Replace your code with this:
MimeBodyPart messageBodyPart = new MimeBodyPart();
String srcFile = System.getProperty("user.dir") + "/Reports/Report.zip";
messageBodyPart.attachFile(srcFile, "application/zip", "base64");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);

Java email content is empty

I have snippet of codes where I send out email with excel file attachment. All works fine where I can see title and even the file attachment. The only thing does not appear is the email content. I have tested that my emailContent variable is not empty. What else can I do to make it appear ? I have even enabled this line of codes messageBodyPart.setText(emailContent); yet the same.
But if enabled this part multipart1.addBodyPart(emailContent); I get error
error: no suitable method found for addBodyPart(String)
multipart1.addBodyPart(emailContent);
try
{
Message emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(origin1));
emailMessage.addRecipient(Message.RecipientType.TO,new InternetAddress(receiptnt1));
emailMessage.addRecipient(Message.RecipientType.TO,new InternetAddress(receiptnt2));
emailMessage.setRecipients(Message.RecipientType.CC,InternetAddress.parse(cc1));
emailMessage.setSubject(emailTitle);
emailMessage.setText(emailContent);
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
//messageBodyPart.setText(emailContent);*/
Multipart multipart1 = new MimeMultipart();
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart1.addBodyPart(messageBodyPart);
// Put parts in message
emailMessage.setContent(multipart1);
//System.out.println("\n\nSend email :"+eMArray[0]);
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
}
catch (Exception e)
{
System.out.println("Transport Problem");
e.printStackTrace();
}
You have initialized
BodyPart messageBodyPart = new MimeBodyPart();
Two times. And before the second initialization you're adding the body contents.
So remove the line
messageBodyPart = new MimeBodyPary();
Line and it will work fine.
Use the following code.
Message emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(origin1));
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiptnt1));
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiptnt2));
emailMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc1));
emailMessage.setSubject(emailTitle);
// emailMessage.setText(emailContent);
Multipart multipart1 = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(emailContent);
// Part two is attachment
BodyPart attachment = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
attachment.setDataHandler(new DataHandler(source));
attachment.setFileName(filename);
multipart1.addBodyPart(attachment);
multipart1.addBodyPart(messageBodyPart);
// Put parts in message
emailMessage.setContent(multipart1);
//System.out.println("\n\nSend email :"+eMArray[0]);
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());

Categories