When I am receiving mail I am getting question mark for all the characters. I am confused where I am getting wrong. There are attachmnets which are displaying correctly only the charcters are getting displayed ???? like question mark. I have verified the body is correctly getting converted to all the asian language but before sending a mail when I again verified the message they were displaying ??.
public void addAttachmentsforMail(String text, MimeMessage message, List<File> attachments, MimeSubtype mimeSubtype) throws MessagingException {
MimeBodyPart mbpText = new MimeBodyPart();
mbpText.setHeader("Content-Type", "text/plain;charset=utf-8");
//I have verified till here the body is getting converted to respective asian languages
if(mimeSubtype.equals(MimeSubtype.HTML)) {
mbpText.setDataHandler(new DataHandler(new ByteArrayDataSource(body, "text/html")));
}
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbpText);
MimeBodyPart mimeAttachment;
for (File file : attachment) {
mbpAttachment = new MimeBodyPart();
FileDataSource foo = new FileDataSource(file);
mimeAttachment.setDataHandler(new DataHandler(foo));
mimeAttachment.setHeader("Content-ID","<" + foo.getName() + ">");
mimeAttachment.setFileName(foo.getName());
mp.addBodyPart(mimeAttachment);
}
//But When I verify the message in log at here before sending the mail all the charcters were converted in to ???
message.setContent(mp);
transport.send(message)
}
This is the header of the mail
Message-ID: <-1251496143.10677.1468164058574.JavaMail.star#gmail.com>
Subject: =?UTF-8?B?5biQ5oi35Y+K5a+G56CB5o+Q6YaS?=
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="----=_Part_10649_-1456564573.1468164040753"
------=_Part_10649_-1456564573.1468164040753
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit
The mbpText.setHeader call is having no effect because of the following mbpText.setDataHandler. If possible, use the setText methods that allow you to specify a charset. You might also want to set the System property "mail.mime.charset" to "utf-8".
Related
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.
I try to send an email with an attachment (A pdf file), but the receiver receives a file with a different name and without the .pdf ending. The name of the file is in Greek..
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("from#mail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail));
message.setSubject(title,"utf-8");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "file.pdf";
String f = name + " Πρόγραμμα Ιανουάριος 2016.pdf"; // the desired name of the file
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(MimeUtility.encodeText(f, "UTF-8", null));
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
Transport.send(message);
System.out.println("Mail " + mail +" sent");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
the name is a string variable and is getting a value previously. The strange is that if I have String f = name + " αααα.pdf" the receiver is getting a pdf succesfully with the name Ρουβάς αααα.pdf but if i have this String f = name + " Πρόγραμμα Ιανουάριος 2016.pdf"; he doesn't. He is getting sth like
=_UTF-8_B_zpzOtc Dz4POsc67zrHPgiDOmc6xzr3Ov8 FzqzPgc65zr_Pgi___ ___filename_1=__5wZGY=_=
I added the message.writeTo(System.out); and I got:
MIME-Version: 1.0
Content-Type: multipart/mixed;
bou
ndary="----=_Part_0_1825884453.1457025565509"
------=_Part_0_1825884453.1457025565509
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
This is message body
------=_Part_0_1825884453.1457025565509
Content-Type: application/octet-stream;
name*0="=?UTF-8?B?zpzOtc+Dz4POsc67zrHPgiDOmc6xzr3Ov8+FzrHPgc6vzr/Pgi";
name*1="Ay?=
=?UTF-8?B?MDE2zpnOsc69zr/Phc6sz4HOuc6/z4IgMjAxNi5wZGY=?";
name*2="="
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename*0="=?UTF-8?B?zpzOtc+Dz4POsc67zrHPgiDOmc6xzr3Ov8+FzrHPgc6vzr/Pgi";
filename*1="Ay?=
=?UTF-8?B?MDE2zpnOsc69zr/Phc6sz4HOuc6/z4IgMjAxNi5wZGY=?";
filename*2="="
with props.setProperty("mail.mime.encodeparameters", "false"); or true
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="----=_Part_0_797681969.1457074816557"
------=_Part_0_797681969.1457074816557
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
This is message body
------=_Part_0_797681969.1457074816557
Content-Type: application/octet-stream; name="?????????? 2016.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename*=Cp1252''%3F%3F%3F%3F%3F%3F%3F%3F%3F%3F%202016.pdf
Because you're encoding the filename yourself, you're using the non-standard MIME encoding format, as described in the JavaMail FAQ. That non-standard encoded text is then being split into multiple parameters using the standard RFC 2231 technique. It's this mix of non-standard and standard format that's probably causing the confusion for the mail reader.
Try letting JavaMail do the encoding for you by removing the call to MimeUtility.encodeText. If that doesn't work, set the System property mail.mime.encodeparameters to false to disable the RFC 2231 encoding.
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.
From http://www.oracle.com/technetwork/java/faq-135477.html#sendmpa:
You'll want to send a MIME multipart/alternative message. You
construct such a message essentially the same way you construct a
multipart/mixed message, using a MimeMultipart object constructed
using new MimeMultipart("alternative"). You then insert the text/plain
body part as the first part in the multpart and insert the text/html
body part as the second part in the multipart. You'll need to
construct the plain and html parts yourself to have appropriate
content. See RFC2046 for details of the structure of such a message.
Can someone show me some sample code for this?
This is a part of my own code:
final Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(senderAddress, senderDisplayName));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(m.getRecipient(), m.getRecipientDisplayName()));
msg.setSubject(m.getSubject());
// Unformatted text version
final MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(m.getText(), "text/plain");
// HTML version
final MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(m.getHtml(), "text/html");
// Create the Multipart. Add BodyParts to it.
final Multipart mp = new MimeMultipart("alternative");
mp.addBodyPart(textPart);
mp.addBodyPart(htmlPart);
// Set Multipart as the message's content
msg.setContent(mp);
LOGGER.log(Level.FINEST, "Sending email {0}", m);
Transport.send(msg);
Where m is an instance of my own class.
Using the code below i can send an email written in non-english and although the subject appears correctly the body appears as gibberish.
Any ideas?
Thank you
public void postMail(String recipient, String subject, String message, String from) throws MessagingException, UnsupportedEncodingException {
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "mail.infodim.gr");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress addressTo=new InternetAddress(recipient);
msg.setRecipient(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
Try:
msg.setContent(message, "text/plain; charset=UTF-8");
Edit Changed to text/plain.
Instead of
msg.setContent(message, "text/plain");
I would write
Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(message, "text/plain; charset=ISO-8859-7");
mp.addBodyPart(mbp);
msg.setContent(mp);
I guessed ISO-8859-7 from your name because this charset is for Greek, but maybe you can choose it more properly. Or maybe also UTF-8 works for your case.
If nothing else helps, try changing an encoding of your source files (including .java files) to UTF8.
In Eclipse it is done via Window -> Preferences -> General -> Workspace : Text file encoding
I had CP1252 as a default for my text files.
I am getting my text from .properties files. Changing them to UTF8 didn't help.
This is insane, but switching my .java files to UTF8 solved my issue!