Thank you for reading my post.
I need to automatically send emails which contain:
a company logo (an image),
an HTML message,
a PDF attachment.
I do not manage to have both the image displayed properly in the email, and the PDF "managed properly" by the email client.
CASE 1
(See code below) With multipart = new MimeMultipart("mixed");
the PDF attachment is managed properly by the email client:
a little paper clip appears in the email client to indicate that email has an attachment,
the size of the PDF attachment appears too,
etc.
the logo isn't displayed properly at the top of the email (within the HTML code) but at the end of the email.
CASE 2
(See code below) When multipart = new MimeMultipart("related");
This is the reverse:
the image is displayed at the top of the email where it is supposed to be,
but the PDF attachment is not properly handled by the email client (no paper clip in the main windows, "size unknown" for the attachment, etc.).
I regularly receive emails which contain both a logo and a PDF attachment (as most of us do).
I have noticed (in the messages source of these emails) that there usually are two parts: one multipart/mixed and one multipart/related.
I do not manage to write the code for which both the logo and the attachment are handled properly by the email client.
Below you can find the code I already wrote.
Thank you for helping and best regards.
public void send(String s_fromEmailAddress, String s_toEmailAddress, String s_messageSubject, String s_messageAttachmentFileName, String s_messageAttachmentFileNameToDisplay)
throws AddressException, MessagingException, IOException
{
Properties properties = null;
Session session = null;
Message message = null;
BodyPart messageBodyPart = null;
Multipart multipart = null;
DataSource fileDataSource = null;
String s_htmlText = null;
DataSource fds = null;
//------------------------------------------------------------------
// Get system properties.
//------------------------------------------------------------------
properties = System.getProperties();
//------------------------------------------------------------------
// Setup mail server.
//------------------------------------------------------------------
properties.setProperty("mail.smtp.host", "smtp.wanadoo.fr");
//------------------------------------------------------------------
// Get the default Session object.
//------------------------------------------------------------------
session = Session.getDefaultInstance(properties);
//------------------------------------------------------------------
// Define message.
//------------------------------------------------------------------
message = new MimeMessage(session);
message.setFrom(new InternetAddress(s_fromEmailAddress));
message.addRecipient(
Message.RecipientType.TO,
new InternetAddress(s_toEmailAddress));
message.setSubject(s_messageSubject);
//------------------------------------------------------------------
// Create the message part.
//------------------------------------------------------------------
multipart = new MimeMultipart("related");
//------------------------------------------------------------------
// HTML part
//------------------------------------------------------------------
s_htmlText =
"<html> \n"
+ " <head> \n"
+ " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"> \n"
+ " </head> \n"
+ " <body> \n"
+ " <img width=\"100px\" \n"
+ " height=\"37px\" \n"
+ " style=\"margin-left: 1em;\" \n"
+ " src=\"cid:image\" \n"
+ " alt=\"LOGO\" />\n"
+ " <br /> \n"
+ ms_messageBodyPartText
+ " </body> \n"
+ "</html> ";
messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(s_htmlText, "text/html; charset=utf-8");
messageBodyPart.setHeader("Content-Transfer-Encoding", "8bit");
multipart.addBodyPart(messageBodyPart);
//------------------------------------------------------------------
// Logo (image)
//------------------------------------------------------------------
messageBodyPart = new MimeBodyPart();
fds = new FileDataSource("where_the_image_can_be_found//Logo1_25_p_cent.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<image>");
messageBodyPart.addHeader("Content-Type", "image/png");
multipart.addBodyPart(messageBodyPart);
//------------------------------------------------------------------
// This part is the attachment.
//------------------------------------------------------------------
if((s_messageAttachmentFileName != null)
&& (s_messageAttachmentFileNameToDisplay != null))
{
messageBodyPart = new MimeBodyPart();
fileDataSource = new FileDataSource(s_messageAttachmentFileName);
messageBodyPart.setDataHandler(new DataHandler(fileDataSource));
messageBodyPart.addHeader("Content-Type", "application/pdf");
messageBodyPart.setFileName(s_messageAttachmentFileNameToDisplay);
multipart.addBodyPart(messageBodyPart);
}
//------------------------------------------------------------------
// Put parts in message.
//------------------------------------------------------------------
message.setContent(multipart);
//------------------------------------------------------------------
// Send the message
//------------------------------------------------------------------
Transport.send(message);
}
Related
I tried in many ways to get the reply in same thread using outlook account and javamail api but iam not able to get reply in same thread instead iam getting as attachment.
I tried to copy whole content and save in current message even then iam getting as attachment, also tried to change the content disposition as inline still it didn't work
you can find the code below which i had tried.
Properties properties = new Properties();
Session emailSession = Session.getDefaultInstance(properties,null);
store = emailSession.getStore("imaps");
store.connect(host,mailbox_username, mailbox_password);
folder = store.getFolder("Inbox");
folder.open(Folder.READ_WRITE);
Message[] unreadMessages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN),false));
if(unreadMessages.size()>0)
{
for (int i = 0; i < unreadMessages.length; i++)
{
log.info("retriving message "+(i+1))
Message message = unreadMessages[i]
Address[] froms = message.getFrom();
String senderEmailAddress =(froms[0]).getAddress();
if(senderEmailAddress.endsWith("#gmail.com"))
{
subject = message.getSubject()
log.info(message.getSubject())
}
else
{ //reply to same mail here we need to reply to the message
Message message2 = new MimeMessage(emailSession);
message2= (MimeMessage) message.reply(false);
message2.setSubject("RE: " + message.getSubject());
//message2.setFrom(new InternetAddress(from));
message2.setReplyTo(message.getReplyTo());
message2.addRecipient(Message.RecipientType.TO, new InternetAddress(senderEmailAddress));
BodyPart messageBodyPart = new MimeBodyPart();
content = "some reply message"
//multipart.addBodyPart(content);
messageBodyPart.setText(content);
Multipart multipart = new MimeMultipart("related");
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
//messageBodyPart.setDataHandler(message.getDataHandler());
//bodyPart.setDataHandler(new DataHandler(ds));
//messageBodyPart.setHeader("Content-Type", "image/jpeg; name=image.jpg");
//messageBodyPart.setHeader("Content-ID", "<image>");
//messageBodyPart.setHeader("Content-Disposition", "inline");
//messageBodyPart.addBodyPart(bodyPart);
//msg.setContent(content);
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
messageBodyPart.setContent(message, "message/rfc822");
messageBodyPart.setDataHandler(message.getDataHandler());
// Add part to multi part
multipart.addBodyPart(messageBodyPart);
// Associate multi-part with message
message2.setContent(multipart);
Transport t = emailSession.getTransport("smtp");
try {
t.connect(mailbox_username, mailbox_password);
t.sendMessage(message2, message2.getAllRecipients());
} finally {
t.close();
}
}
}
}
"inline" vs. "attachment" is just advice for the mail reader. Many ignore the device, or aren't capable of displaying all content types inline.
If you want the text of the original message to appear in the body of the reply message (e.g., indented with ">"), you need to extract the original text and reformat it appropriately, adding it to the text of the reply, then set that new String as the content of the reply message.
I am using this code to send an excel file through Outlook using Java.
The excel is generated through another Java Code.It has been generated Properly.
When i use this code then the recipient receives the attachment in undefined Format.Please help
try {
msg.setFrom();
java.util.Date date=new java.util.Date();
fromAddress = new InternetAddress(from);
msg.setFrom(fromAddress);
//msg.addRecipient(Message.RecipientType.CC, to);
msg.setSubject("For Testing Purpose "+date);
//msg.setSentDate(new Date());
msg.setText("Attachment");
/*
* ************************Test for
* attachment*************************
*/
String fileAttachment = "D://testing.xlsx";
// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
String bodytext = "Hi,<br>";
bodytext = bodytext +"<br>";
bodytext = bodytext
+ "Please find Attachnment for last week Reviewr's "+date
+ "<br>"+"</Font><br><br><br>Thanks<br>Gulshan Raj";
messageBodyPart.setContent(bodytext , "text/html");
// Part two is attachment
DataSource source = new FileDataSource(fileAttachment);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName("Reviewers Data");
// Put parts in message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachmentBodyPart);
msg.setContent(multipart);
/* ******************************************************************** */
Transport.send(msg);
System.out.println("2^^^^^^^fileAttachment "+fileNm);
System.out.println("2^^^^^^^bodytext "+bodytext);
} catch (MessagingException mex) {
System.out.println("2^^^^^^^^^^^^^^^^^^^send failed, exception: "+ mex);
}
Attachments appear well except on iphone when I add an image as MimeBodyPart.INLINE , what is the best way to attach an image as signature using javamail?
If I remove "imagePart", all other attachments work well
I used :
MimeMessage m = new MimeMessage(session);
MimeMultipart content = new MimeMultipart("related");
// ContentID is used by both parts
String cid = ContentIdGenerator.getContentId();
// HTML part
String textPartSaine = Tools.convertSymbolToUTF8(emailContenu, true);
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("<html><head>"
+ "<title></title>"
+ "</head>\n"
+ "<body>"
+ "<div>"+ textPartSaine.replaceAll("\n", "<BR/>") +"</div><BR/><BR/>"
+ "<div><img src=\"cid:"
+ cid
+ "\" /></div><BR/><BR/>" + "</body></html>",
"US-ASCII", "html");
content.addBodyPart(textPart);
// Image part
if(signature != null && signature.exists()){
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.attachFile(signature);
imagePart.setContentID("<" + cid + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
content.addBodyPart(imagePart);
}
if(fichiers != null && fichiers.length > 0) {
for(i = 0; i < fichiers.length; i++) {
partie = new MimeBodyPart();
partie.attachFile(fichiers[i]);
content.addBodyPart(partie);
}
}
Thanks
Solved
multipart/mixed (Will contain text and attachments)
multipart/alternative (Will contain text and HTML)
multipart/related (HTML + embedded images)
image1 (Content-Id: xxx)
image2
...
attachment 1
attachment 2
...
I am currently trying to send an email with a picture inside the mail using the Google App Engine 1.9.5. This features is availible only from the version 1.9.0 of the SDK :
Users now have the ability to embed images in emails via the Content-Id attachment header.
https://code.google.com/p/googleappengine/issues/detail?id=965
https://code.google.com/p/googleappengine/issues/detail?id=10503
Source : https://code.google.com/p/googleappengine/wiki/SdkForJavaReleaseNotes
This is my code :
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("leo.mieulet#xxx.com", "xxx.com newsletter"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("leo.mieulet#xx.com", "Leo Mieulet"));
msg.setSubject("Inline image test : "+new Date().getTime());
String imageCid = "graph";
DataSource ds = new ByteArrayDataSource(imageBase64, "image/png");
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setDataHandler(new DataHandler(ds));
imagePart.setFileName(imageCid + ".png");
imagePart.setHeader("Content-Type", "image/png");
imagePart.addHeader("Content-ID", "<" + imageCid + ">");
String htmlBody = "My html text... <img src=\"cid:"+imageCid+"\"> ... ends here.";
// Create alternate message body.
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<html><body>"+htmlBody+"</body></html>", "text/html");
final Multipart multipart = new MimeMultipart();
multipart.addBodyPart(htmlPart);
multipart.addBodyPart(imagePart);
msg.setContent(multipart);
msg.saveChanges();
Transport.send(msg);
I receive an email which looks like :
Could anyone help me with the problem ?
Based on the imageBase64 variable name, you seems to give to the ByteArrayDataSource the image already encoded in Base64. You should directly use the image byte array without Base64.encode() it.
Awesome ! ;)
If you want to display the image in pure HTML ( in app-engine doGet() context ) :
//byte[] imgContent = the content of your image
Base64 base64 = new Base64();
imgContent = base64.encode(imgContent);
resp.getWriter().write("<html><img src='data:image/png;base64,"+new String(imgContent)+"'></html>");
And as said #benoit-s, you don't need to encode in base64 the content of your image.
I just edited this line :
DataSource ds = new ByteArrayDataSource(imageBase64, "image/png");
to
//byte[] imageAsByteArray = the content of your image
DataSource ds = new ByteArrayDataSource(imageAsByteArray, "image/png");
I want to attach multiple files inside a calendar invite using java.
Currently i am able to create an invite with the html body text but i am not able to add attachments to that invite.
Does anyone knows how to attach files.
I am not sending the invite as attachment. It is going as normal accept/decline way.
Please post ASAP .
Thanks in advance
CODE AS FOLLOWS :
MimetypesFileTypeMap mimetypes = (MimetypesFileTypeMap) MimetypesFileTypeMap.getDefaultFileTypeMap();
mimetypes.addMimeTypes("text/calendar ics ICS");
MailcapCommandMap mailcap = (MailcapCommandMap) MailcapCommandMap.getDefaultCommandMap();
mailcap.addMailcap("text/calendar;; x-java-content-handler=com.sun.mail.handlers.text_plain");
Properties props = new Properties();
props.setProperty("mail.transport.protocol", " ");
props.setProperty("mail.host", mailServer);
//props.setProperty("mail.user", "emailuser");
//props.setProperty("mail.password", "");
Session mailSession = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(mailSession);
//message.addHeaderLine("text/calendar;method=REQUEST;charset=UTF-8");
/* String emailAddress = invite_email;
String fullName = invite_name;*/
String emailAddress = "XYZ#aBC.com";
String fullName = "ABCD";
message.setFrom(new InternetAddress(replyEmail, replyEmailName));
javax.mail.Address address = new InternetAddress(emailAddress, fullName);
message.addRecipient(MimeMessage.RecipientType.TO, address);
message.setSubject("abc" + invite_sub);
// Create a Multipart
Multipart multipart = new MimeMultipart("alternative");
//part 1, html text
BodyPart messageBodyPart = buildHtmlTextPart(team_id);
multipart.addBodyPart(messageBodyPart);
// Add part two, the calendar
BodyPart calendarPart = buildCalendarPartNew(emailAddress , fullName , invite_sub , invite_uuid ,start_date , finish_date , invite_seq , invite_status , invite_timezone );
multipart.addBodyPart(calendarPart);
// Add attachments to the body
multipart = addAttachment(multipart,Req_List);
//update the requisition id list back to " " once the attachment process is over
Req_List = " ";
// Put parts in message
System.out.println("setting the content of message");
message.setContent(multipart);
// send message
try {
Transport transport = mailSession.getTransport();
transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
}
catch (Exception ex) {
System.out.println(ex.toString());
throw ex;
}
THE FUNCTION FOR ATTACHMENT MAINLY CONTAINS :
FileDataSource fds1 = new FileDataSource(sharepath_name);
attachment.setDataHandler(new DataHandler(fds1));
attachment.setFileName(fds1.getName());
attachment.setHeader("MIME-Version", "1.0");
attachment.setHeader("Content-Type", " "+mime_type+ "; name=\"" + sharepath_name + "\"");
attachment.setHeader("Content-Disposition", "attachment; filename=\"" + sharepath_name + "\"");
attachment.setHeader("Content-Transfer-Encoding", "base64");
multipart.addBodyPart(attachment);
return multipart;
there is no error as such , the invite is getting generated with the text , but the main problem is i want attachments inside the invite, i am not able to attach files inside the invite, i don't know how to attach files inside invite ?
Also the attachments i need to provide multiple attachments inside the invite.
Thanks in advance
Have you tried without setting the attachment headers manually? They should be set by MimeMessage.