Java mail is not supporting foreign languages - java

I need to send HTML having content in different languages. my configuration are :
MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_Part_18_19002270.1337852743826"
------=_Part_18_19002270.1337852743826 Content-Type: text/html; charset=Cp1252 Content-Transfer-Encoding: quoted-printable
and in mail am getting all characters as ?. Can anybody suggest me how to set encoding so that i could get mail in proper language.
Thanks
found the solution:)
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(bodyText, "UTF-8");
htmlPart.setText(bodyText, "utf-8");
htmlPart.setHeader("Content-Type","text/html; charset=\"utf-8\"");
htmlPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
Still am not able to encode Subject line.

This piece of code might help you. :)
MimeMessage msg = new MimeMessage(session);
msg.setSubject("yourSubject", "UTF-8"); // here you specify your subject encoding
msg.setContent("yourBody", "text/plain; charset=utf-8");
msg.setFrom("senderAddress");
msg.addRecipient(Message.RecipientType.TO, "recieverAddress");
Transport.send(msg);
EDIT:
Here is the method I've used to set the encoding of subject line.

Convert whole html File read string to UniCode
I used the below code to convert Whole HTML File read as String using FileUtils
String contents = FileUtils.readFileToString(new File("/path/to/the/HTMLfile"), "UTF-8")
I was trying to send an Email in Chinese, Arabic, Japanese and Spanish. So while sending I was unable to figure it out while setting Content in MimeMessage and MimeMultipart
So, I read the whole file as a string and then check whether the character lies between 1-128 i.e. ASCII equivalent characters (Numeric Special Characters Space etc..) that belong to ASCII. I retained them in the string and rest all characters are converted to Unicode
Function to convert html file string to Unicode string and is then set in mime body part and mime multipart. Hope it is very clear
public String convertToUniCode(String yourHTMLBodyStr) {
String str = "<div>Chinese 你好嗎 English How are you Japanese お元気ですか Arabic كيف حالك Spanish cómo estás</div>";
String[] codePointAt = new String[str.length()];
for (int j = 0; j < str.length(); j++) {
int charactercode = Character.codePointAt(str, j);
if (charactercode > 0 && charactercode < 128) {
codePointAt[j] = String.valueOf(str.charAt(j));
} else {
codePointAt[j] = "&#" + String.valueOf(charactercode) + ";";
}
}
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < codePointAt.length; i++) {
strBuilder.append(codePointAt[i]);
}
System.out.println("New String :: " + strBuilder.toString());
}
Output(Unicode String) with &# Like &#16003 :
New String :: Chinese 你好嗎 English How are you Japanese お元気ですか Arabic كيف حالك Spanish cómo estás
MimeMessage msg = new MimeMessage(session);
String htmlUnicodeStr = convertToUniCode(yourHTMLBodyStr);
msg.setSubject(UniCodeSubject, "UTF-8"); // here you specify your subject encoding
Multipart emailMimeMultipart;
MimeBodyPart messageBody = new MimeBodyPart();
messageBody.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlUnicodeStr, "text/html")));
emailMimeMultipart.addBodyPart(messageBody);
//Add UTF-8 In MimeMultiPart While Setting Content and Transport.Send()

Try to switch charset=Cp1252 to charset=UTF-8.

Related

java StringBuffer send email some part html some part java format updated

Message msg = new MimeMessage(mailSession);
try{
msg.setSubject("Test Notification");
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(sentTo, false));
StringBuffer updated= new StringBuffer(
String str1 = String.format("%d", 101) +
String str2 = String.format("%s", "Amar Singh") +
String str3 = String.format("%f", 101.00)+
String str4 = String.format("%x", 101)+
String str5 = String.format("%c", 'c')+
"<p style=\"color:red;\">BRIDGEYE</p>");
String regular_message = Str1+str2+str3+str4+str5;
//msg.setText(reguar_mesage);
msg.setContent(updated, "text/html; charset=utf-8");
msg.setSentDate(new Date());
Transport.send(msg);
}catch(MessagingException me){
logger.log(Level.SEVERE, "sendEmailNotification: {0}", me.getMessage());
}
Hi All,
So I'm trying to send an email that is half java part half html content. My html part is no longer in this code. I just didn't want to copy and paste it cause it gets long and really complex lol.
So I tried set text for the regular part then set content for the html part but the set content override the set text. So the set text is not showing up on email. I then try combining both strings in set content. But the regular java part gets converted to html.
How would I do half java format. half html?
Thanks in advance
UPDATE I change it to a string buffer
as you can see some parts of my string buffer has html some has java format
when I send the email it just gets convert to html. How do I keep the html html,
and java java format. Much thanks appreciated

Javamail Getting one extra file On downloading attachments

I'm getting one extra file of type File on downloading attachments. I'm using MimeBodyPart.saveFile() here is my download attachment code
for (MimeBodyPart mbp : msgToDownload.getAttachmentList()) {
updateProgress(msgToDownload.getAttachmentList().indexOf(mbp),
msgToDownload.getAttachmentList().size());
mbp.saveFile(DOWNLOAD_LOCATION + mbp.getFileName());
}
here msgToDownload is a Class that take Message msg as parameter with some other parameters. And getAttachmentList() is a list of type MimeBodyPart defined as List<MimeBodyPart>
This is how I'm adding attachments to list
sb.setLength(0);
msgToRender.clearAttachments();
Message msg = msgToRender.getMsgRef();
try {
// String messageType = msg.getContentType();
sb.append(getText(msg));
if (hasAttachments(msg)) {
Multipart mp = (Multipart) msg.getContent();
for (int i = mp.getCount() - 1; i >= 0; i--) {
BodyPart bp = mp.getBodyPart(i);
MimeBodyPart mbp = (MimeBodyPart) bp;
msgToRender.addAttachment(mbp);
}
}
}catch(Exception e){
}
Extra file contain attributes of text part of the Mail. Content of extra file
-001a114fd0aa0b377d0546bb84a0 Content-Type: text/plain; charset=UTF-8 please find the attachments... --001a114fd0aa0b377d0546bb84a0 Content-Type: text/html; charset=UTF-8 please find the attachments... --001a114fd0aa0b377d0546bb84a0--
First, you should learn about the isMimeType method.
The problem is most likely that you're not handling multipart/alternative messages. See the sample code in the JavaMail FAQ.

How to get filename of all attachements of email?

I am trying to get the filename of all the attachements of emails using java and imap.My code is:
MimeMessage msg = (MimeMessage) messages[i];
String fileName = msg.getFileName();
System.out.println("The file name of this attachment is " + fileName);
but it prints null always even if email contain attachment..I have seen different codes on SO but none worked...and I don't know what to do if attachment is more than one .
PS:I only want to get the filename and don't want to download attachments.
First, to determine if a message may contain attachments using the following code:
// suppose 'message' is an object of type Message
String contentType = message.getContentType();
if (contentType.contains("multipart")) {
// this message may contain attachment
}
Then we must iterate through each part in the multipart to identify which part contains the attachment, as follows:
Multipart multiPart = (Multipart) message.getContent();
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
// code to save attachment...
}
}
And to save the file, you could do:
part.saveFile("D:/Attachment/" + part.getFileName());
Source
there is an easier way with apache commons mail:
final MimeMessageParser mimeParser = new MimeMessageParser(mimeMessage).parse();
final List<DataSource> attachmentList = mimeParser.getAttachmentList();
for (DataSource dataSource: attachmentList) {
final String fileName = dataSource.getName();
System.out.println("filename: " + fileName);
}
I was facing the same issue when the email contained another email as an attachment. The content-disposition of such an attachment does not contain fileName.
String contentType = message.getContentType();
List<String> attachmentFiles = new ArrayList<String>();
if(contentType.contains("multipart"))
{
Multipart multiPart = (Multipart)message.getContent();
int numberOfParts = multiPart.getCount();
for(int partCount = 0; partCount < numberOfParts; partCount++)
{
MimeBodyPart part = (MimeBodyPart)multiPart.getBodyPart(partCount);
if(Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
String fileName = part.getFileName();
String extension = FilenameUtils.getExtension(fileName);
//If the attachment is an email, fileName will be null.
if ("message/rfc822".equalsIgnoreCase(part.getContentType())) {
MimeMessage tempMessage = new MimeMessage(null, part.getInputStream());
fileName = tempMessage.getSubject()+".eml"; //all the email attachments will be converted to .eml format.
extension = "eml";
}
File tempEmailFile = File.createTempFile(messageId + "_" + partCount , "." + extension);
part.saveFile(tempEmailFile);
attachmentFiles.add(fileName);
attachmentFiles.add(tempEmailFile.getAbsolutePath());
}
}
}
Reference: javamail also extract attachments of encapsulated message Content-Type: message/rfc822

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

Attachment Id of emails in java

I am currently working with java mail api . I need to list the attachment details also wants remove the attachment from some emails and forward it to others. So i'm trying to find out the Attachment ID. How can i do it? Any suggestion will be appreciate!!!
Does this help?
private void getAttachments(Part p, File inputFolder, List<String> fileNames) throws Exception{
String disp = p.getDisposition();
if (!p.isMimeType("multipart/*") ) {
if (disp == null || (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE)))) {
String fileName = p.getFileName();
File opFile = new File(inputFolder, fileName);
((MimeBodyPart) p).saveFile(opFile);
fileNames.add(fileName);
}
}
}else{
Multipart mp = (Multipart) p.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++){
getAttachments(mp.getBodyPart(i),inputFolder, fileNames);
}
}
}
There ain't anything as an attachment ID. What your mail client displays as a message with attached contents, is really a MIME Multipart and looks like this (sample source):
From: John Doe <example#example.com>
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="XXXXboundary text"
This is a multipart message in MIME format.
--XXXXboundary text
Content-Type: text/plain
this is the body text
--XXXXboundary text
Content-Type: text/plain;
Content-Disposition: attachment; filename="test.txt"
this is the attachment text
--XXXXboundary text--
Important things to note:
Every part in a multipart has a Content-Type
Optionally, there can be a Content-Disposition header
Single parts can be themselves multipart
Note that there is indeed a Content-ID header, but I don't think it's what you are looking for: for example, it is used in multipart/related messages to embed image/*s and text from a text/html in the same email message. You have to understand how it works and if it's used in your input.
I think your best option is to examine the Content-Disposition and the Content-Type header. The rest is guesswork, and without actual requirement one can't help with the code.
Try using the Apache Commons Email package which has a MimeMessageParser class. With the parser you can get the content id (which could be used to identify the attachment) and attachments from the email message like so:
Session session = Session.getInstance(new Properties());
ByteArrayInputStream is = new ByteArrayInputStream(rawEmail.getBytes());
MimeMessage message = new MimeMessage(session, is);
MimeMessageParser parser = new MimeMessageParser(message);
// Once you have the parser, get the content ids and attachments:
List<DataSource> attachments = parser.getContentIds.stream
.map(id -> parser.findAttachmentByCid(id))
.filter(att -> att != null)
.collect(Collectors.toList());
I have created a list here for the sake of brevity, but instead, you could create a map with the contentId as the key and the DataSource as the value.
Take a look at some more examples for using the parser in java here, or some code I wrote for a scala project here.

Categories