Inline image shown as attachment : JavaMail - java

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/>

Related

Outlook can't show image into MimeMessage

I prepare my message as MimeMessage and try it open in different mail clients. In all client my message looks good but in Outlook and in another one, it looks wrong
...
MimeMessage mimeMessage = new MimeMessage(session);
// Text version
final MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(email.getPlainMessage(), "text/plain");
// HTML version
final MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(email.getMessage(), "text/html");
//logo
PreencodedMimeBodyPart logo = new PreencodedMimeBodyPart(BASE_64_ENCODING);
logo.setHeader("Content-Type", IMAGE_PNG_CONTENT_TYPE + "; name=\"logo.png\"");
logo.setHeader("Content-ID", "<logo.png#01CFFF81.C72F8000>");
logo.setHeader("Content-Disposition", "inline; filename=\"logo.png\"");
logo.setHeader("Content-Transfer-Encoding", BASE_64_ENCODING);
logo.setContent(ENCODED_LOGO, IMAGE_PNG_CONTENT_TYPE);
// Create the Multipart. Add BodyParts to it.
final Multipart mp = new MimeMultipart("alternative");
mp.addBodyPart(logo);
mp.addBodyPart(textPart);
mp.addBodyPart(htmlPart);
if (Objects.nonNull(email.getFilesToAttach())) {
for (String filename : email.getFilesToAttach()) {
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename.substring(filename.lastIndexOf(File.separator) + 1));
mp.addBodyPart(messageBodyPart);
}
}
// Set Multipart as the message's content
mimeMessage.setContent(mp);
mimeMessage.setSubject(email.getSubject());
mimeMessage.setFrom(new InternetAddress(emailConfig.getNoReplyEmailAddress()));
if (!emailConfig.getNoReplyEmailAddress().equals(email.getFromAddress())) {
List<Address> replyTo = Arrays.asList(new InternetAddress(email.getFromAddress()));
mimeMessage.setReplyTo(replyTo.toArray(new Address[replyTo.size()]));
}
mimeMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email.getToAddress()));
mimeMessage.saveChanges();
...
And when I send it in outlook I see my logo as
but in another mail clients it looks good

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.

JavaMail attachment and body issue

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);

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());

How to attach an object in an email with Java?

I have the following method to send an email, but I couldn't get the attached object, why ?
void Send_Email(String From,String To,String Subject,Text Message_Text,Contact_Info_Entry An_Info_Entry)
{
Properties props=new Properties();
Session session=Session.getDefaultInstance(props,null);
String htmlBody="<Html>Hi</Html>";
byte[] attachmentData;
Multipart multipart=new MimeMultipart();
BASE64Encoder BASE64_Encoder=new BASE64Encoder();
try
{
Message message=new MimeMessage(session);
message.setFrom(new InternetAddress(From,"NM-Java Admin"));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(To,"Ni , Min"));
// You may need to encode the subject with this special method !
// message.setSubject(javax.mail.internet.MimeUtility.encodeText("Testing javamail with french : ��� "));
message.setSentDate(new Date());
message.setSubject(Subject);
MimeBodyPart messageBodyPart=new MimeBodyPart(); // Create the message part
messageBodyPart.setText(Message_Text.getValue()); // Fill message
multipart.addBodyPart(messageBodyPart);
MimeBodyPart htmlPart=new MimeBodyPart();
htmlPart.setContent(htmlBody,"text/html");
multipart.addBodyPart(htmlPart);
//setHTMLContent(message);
ByteArrayOutputStream bStream=new ByteArrayOutputStream();
ObjectOutputStream oStream=new ObjectOutputStream(bStream);
oStream.writeObject(An_Info_Entry);
// attachmentData=bStream.toByteArray();
// attachmentData=BASE64_Encoder.encode(bStream.toByteArray());
MimeBodyPart attachment=new MimeBodyPart();
attachment.setFileName(An_Info_Entry.Contact_Id);
attachment.setContent(BASE64_Encoder.encode(bStream.toByteArray()),"application/x-java-serialized-object");
multipart.addBodyPart(attachment);
setBinaryContent(message,BASE64_Encoder.encode(bStream.toByteArray()).getBytes());
message.setContent(multipart); // Put parts in message
message.setText(Message_Text.getValue()+" [ An_Info_Entry.Contact_Id = "+An_Info_Entry.Contact_Id+" ]");
Transport.send(message);
}
catch (Exception ex)
{
// ...
}
}
Probably because:
You're setting your content type as: text/html and you're really sending raw binary.
MimeBodyPart attachment=new MimeBodyPart();
attachment.setFileName(An_Info_Entry.Contact_Id);
attachment.setContent(attachmentData,"text/html"); // <-- Here
multipart.addBodyPart(attachment);
Even if you use the right content-type, you should encode the content as using base64 that way the attachment could make it trough the net.
// This
//attachmentData=bStream.toByteArray();
// should be something like:
attachmentData=Base64Coder.encode( bStream.toByteArray());

Categories