Incorrect content in mail for HTML data - java

I am trying to send the mail using JavaMailSender which include the html content but instead of the rendered html in the email i am getting the html code itself in the mail i.e
Method used to send email
public void sendMimeMessage(String from, String to, String subject, String messageBody, String... cc) {
MimeMessage message = mailSender.createMimeMessage()
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from)
helper.setSentDate(new Date())
helper.setSubject(subject)
helper.setText(messageBody, true)
helper.setTo(to)
helper.setCc(cc)
mailSender.send(message)
log.debug("Email successfully sent to <${to}> with cc <${cc}> and with subject <${subject}> and Email body: ${messageBody}")
} catch (Exception exception) {
exception.printStackTrace()
log.error("Email to <${to}> with subject <${subject}> could not be sent due to: ", exception)
}
}
Any help would be appreciated.

This might help you.
You can use Apache velicity, or can see my Answer.
Sample code:
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("mail.host.com");
MimeMessage message = sender.createMimeMessage();
// use the true flag to indicate you need a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo("test#host.com");
// use the true flag to indicate the text included is HTML
helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);
// let's include the infamous windows Sample file (this time copied to c:/)
FileSystemResource res = new FileSystemResource(new File("c:/Sample.jpg"));
helper.addInline("identifier1234", res);
sender.send(message);

This worked for me.
Step 1. Construct the messageBody as follows:
Let suppose you need a HTML content in mail like shown below
**SERIAL NO PROCESS_INSTANCE_ID USONUMBER**
1 TSV00876 N89876
2 LMNV0083 V89876
Let suppose you have list from where you are going to populate above columns.
List<Report> list = xyzService.getReport(); **//returns list of Report**
StringBuilder buf = new StringBuilder();
buf.append("<!doctype html>\n");
buf.append("<html lang='en'>\n");
buf.append("<head>\n");
buf.append("<meta charset='utf-8'>\n");
buf.append("<title>Report</title>\n");
buf.append("</head>\n");
buf.append("<body>" +
"<table border ='1'>" + "<tr>" +
"<th>SERIAL NO</th>" +
"<th>PROCESS_INSTANCE_ID</th>" +
"<th>USONUMBER</th>"+
"</tr>\n");
for (int i = 0; i < list.size(); i++) {
buf.append("<tr><td>").
append(list.get(i)).getSerialNo().append("</td><td>").
append(list.get(i).getProcessInstanceId()).append("</td><td>").
append(list.get(i).getUsoNumber()).append("</td><td>").
append("</td></tr>\n");
}
buf.append("</table>\n" +
"</body>\n" +
"</html>");
String messageBody = buf.toString();
Step 2. pass this string messageBody in your method sendMimeMessage() and set
MimeMessageHelper as shown below.
MimeMessage message = mailSender.createMimeMessage()
MimeMessageHelper helper = new MimeMessageHelper(message,MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,StandardCharsets.UTF_8.name());
helper.setText(messageBody, true);

Related

why the reply mail is sent as attachment when I send it to outlook account using javamail?

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.

In multipart mime message how to add some info in first part of the message

I am sending multi-part message using JavaMailSenderImpl.
I have following code to send mail.
MimeMessage mimeMessage = this.mailSender.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
message.setSubject("Testing");
message.setTo(getMktTemplateErrorsReportingEmailAddress());
message.setText("Hello testing.", emailTemplate.isHtml());
if (StringUtils.isNotBlank(fileName)) {
FileSystemResource file = new FileSystemResource(fileName);
message.addAttachment(file.getFilename(), file);
}
this.mailSender.send(mimeMessage);
In send() method ..
Object cObj = mimeMessage.getContent();
if(cObj instanceof Multipart) {
Multipart content = (Multipart)cObj ;
int count = content.getCount();
for(int i=0; i<count; i++) {
BodyPart part = content.getBodyPart(i);
//need to append some info if part is text.
}
My understanding is first part contains message as String and second as fils (attachment). while I am seeing as first part is MimeMultipart.
eg:
javax.mail.internet.MimeMultipart#79a3195f
java.io.FileInputStream#14bedd31
Now my question is How to replace part after appending information.
eg: First part is "Hello testing.". I want to append with as some system info. for eg: As Hello testing. IP: 192.23.22.22 . So after appending how to replace this with first part and send.
Don't know how to do this.

In outloouk, file name received contains wrong characters

In my java application, I want to send an e-mail using the MimeMessageHelper:
My file name is: âTestFileüa.PNG
my code is here:
SimpleMailMessage mail= new SimpleMailMessage(templateMessage);
mail.setTo(personMail);
mail.setSubject(subject);
mail.setText(content);
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper messageHelper = new MimeMessageHelper(message,true);
messageHelper.setFrom(mail.getFrom());
messageHelper.setTo(mail.getTo());
messageHelper.setSubject(mail.getSubject());
messageHelper.setText(mail.getText());
messageHelper.addAttachment(fileName, new ByteArrayResource(attchmentFile));
} catch (MessagingException e) {
e.printStackTrace();
}
The file is correcttly sent, but in outlook, the special characters of my file aren't correctly displayed.
It looks like there is a problem with the encoding of the filename. I would try setting an appropriate character encoding when creating the mime helper object. For example:
MimeMessageHelper messageHelper =
new MimeMessageHelper(message, true, "UTF-8");
before this line,
messageHelper.addAttachment(fileName, new ByteArrayResource(attchmentFile));
I added :
fileName = MimeUtility.encodeText(filename);
and this work perfectly!

Javamail Parsing Email Body with 7BIT Content-Transfer-Encoding

I've been implementing an feature to read email file. If the file have attachment, return attachment name.
Now I'm using Javamail library to parse email file. Here is my code.
public static void parse(File file) throws Exception {
InputStream source = new FileInputStream(file);
MimeMessage message = new MimeMessage(null, source);
Multipart multipart = (Multipart) message.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
String disposition = bodyPart.getDisposition();
if (disposition != null
&& disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
System.out.println("FileName:"
+ MimeUtility.decodeText(bodyPart.getFileName()));
}
}
}
It works fine but when email file have 7bit Content-Transfer-Encoding, bodyPart.getFileName() make NullPointerException.
Is there any way to get attachement name when email is 7bit Content-Transfer-Encoding?
Sorry for my poor English.
Edited: Here is some info about my test file.
(X-Mailer: Mew version 2.2 on Emacs 21.3 / Mule 5.0 (SAKAKI)); (Mime-Version:1.0):(Content-Type: Multipart/Mixed); (Content-Transfer-Encoding: 7bit)
If my answer does not work, show the stack trace.
Use a Session, as that probably is the only thing being null.
Properties properties = new Properties();
Session session = Session.getDefaultInstance(properties);
MimeMessage message = new MimeMessage(session, source);
Not all attachments have a filename. You need to handle that case.
And you don't need to decode the filename.
You can handle the case of "attachments not having a name" in this way:
String fileName = (bodyPart.getFileName() == null) ? "your_filename"
: bodyPart.getFileName();

I want to attach multiple files in outlook calendar invite using java

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.

Categories