JavaMail attachment Decode Exception with Hotmail - java

I am trying to download attachments from Hotmail messages and getting the following exception: com.sun.mail.util.DecodingException: BASE64Decoder: Error in encoded stream: needed 4 valid base64 characters but only got 2 before EOF, the 2 most recent characters were: "JV". for every message with an attachment. I tried setting "mail.imaps.partialfetch" to "false" but it did not work, here is the code i'm using:
public class imapHotmail {
private static Object m;
public static void main(String[] args) {
java.security.Security
.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
//System.setProperty("mail.mime.decodetext.strict", "false");
//System.setProperty("mail.mime.base64.ignoreerrors", "true");
System.setProperty("mail.imaps.partialfetch", "false");
props.setProperty("mail.store.protocol", "imaps");
props.setProperty("mail.imap.ssl.enable", "true");
props.setProperty("mail.imaps.partialfetch", "false");
try {
Session session = Session.getInstance(props, null);
// session.setDebug(true);
Store store = session.getStore("imap");
System.out.println("connecting....");
store.connect("imap-mail.outlook.com", "soemone#hotmail.com", "pass");
System.out.println("connected");
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
Message[] msgs = inbox.getMessages();
int x = 1;
for (Message msg : msgs) {
System.out.println(x);
System.out.println(msg.getSubject());
Object content = msg.getContent();
if (content instanceof Multipart) {
Multipart multipart = (Multipart) content;
for (int i = 0; i < multipart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
System.out.println("saving");
//part.getContent(); this only returns the parts headers and 2 chars from the encoded bodypart
String name = part.getFileName();
File f = new File("C:\\Users\\user\\Desktop\\" + name);
part.saveFile("C:\\Users\\user\\Desktop\\" + name);
System.out.println("saved");
}
}
}
x++;
}
inbox.close(true);
store.close();
} catch (Exception mex) {
mex.printStackTrace();
}
}
here is the output i get if i call part.writeTo(System.out):
Content-Type: application/pdf
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="pdf2.pdf"
JV

Related

How to get Bounced mails in java

I am implementing a Bulk mail application, in this applica This link.
I am able to connect to the server and and send the emails to the destination addresses, but I want to identify the undelivered mails.
By using below program I am able to get the email subjects. But based on the subject it will be difficult to identify the exact undelivered mails.
public static void main(String[] args) {
Properties props = System.getProperties();
props.setProperty("mail.host", host);
props.setProperty("mail.user", user);
props.setProperty("mail.from", from);
//props.setProperty("mail.debug", "true");
//props.setProperty("mail.domain", domain);
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore(protocol);
Session session1 = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
System.out.println((store.isConnected())?"Already Connected":"Not Already Connected");
store.connect(host, port, user, password);
Folder inbox = store.getFolder("INBOX");
System.out.println("folder>>>" + inbox.getFullName() + "<<<");
System.out.println("folder URLName>>>" + inbox.getURLName() + "<<<");
System.out.println((inbox.exists()?"folder exists":"folder does not exist"));
int folderType = inbox.getType();
System.out.println("folder type>>>" + folderType + "<<<");
inbox.open(Folder.READ_WRITE);
System.out.println("Message Count:" + inbox.getMessageCount());
Message[] m = inbox.getMessages();
for (int x = 0; x < m.length; x++) {
System.out.println(m[x].getSubject());
}
inbox.close(false);
store.close();
}catch(Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
How can I get the undelivered mails(Bounced).
I am using Hmailserver as my mail server.
You can use this below code
MimeMessage payload = (MimeMessage) message.getPayload();
Multipart mp = (Multipart) payload.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart bodyPart = mp.getBodyPart(i);
StringWriter writer = new StringWriter();
IOUtils.copy(bodyPart.getInputStream(), writer);
System.out.println("Content inputstream: " + writer.toString());
}

In Javamail Attachment is not displaying

In Javamail Attachment is not displaying
I tried to send a mail with attachment
It sending and received But in received mail attachment is not displaying not display
attachment is blank and
Here the code is:
#Bean
public JavaMailSenderImpl mailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setProtocol("smtp");
javaMailSender.setHost("smtp.gmail.com");
javaMailSender.setPort(587);
javaMailSender.setUsername("*******#gmail.com");
javaMailSender.setPassword("*********");
Properties props = ((JavaMailSenderImpl) javaMailSender).getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
props.put("mail.mime.multipart.allowempty", "true");
javaMailSender.setJavaMailProperties(props);
return javaMailSender;
}
{
message.setSubject(mailServiceDTO.getSubject());
message.setText(mailServiceDTO.getSubject(), "text/html");
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(mailServiceDTO.getSubject(), "text/html");
for (EmailAttachment attachment : mailServiceDTO.getAttachments()) {
message.addAttachment(attachment.getAttachmentName(), new ByteArrayResource(attachment.getAttachmentContent().getBytes()));
}
Multipart mp = new MimeMultipart();
mp.addBodyPart(messageBodyPart);
mimeMessage.setContent(mp);
javaMailSender.send(mimeMessage);
}
you can use MimeMessageHelper in spring mail.
Example
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper mailMessage = null;
List<PathSource> pathSourceList = request.getMailAttachList();
if (pathSourceList != null && pathSourceList.size() > 0)
mailMessage = new MimeMessageHelper(msg, true);
else
mailMessage = new MimeMessageHelper(msg, false);
// ....
if (pathSourceList != null && pathSourceList.size() > 0) {
for (PathSource filepath : pathSourceList) {
ByteArrayResource stream = new ByteArrayResource(DatatypeConverter.parseBase64Binary(
filepath.getData()));
mailMessage.addAttachment(filepath.getFileName(), stream);
}
}
try {
javaMailSender.send(mailMessage.getMimeMessage());
} catch (Exception ex) {
log.error("server info {}", serverModel.toString());
throw ex;
}
Add Multiple attachments..
public static void main(String[] args) {
final String fromEmail = ""; // requires valid gmail id
final String password = "";// correct password for gmail id
final String toEmail = ""; // can be any
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); // SMTP Host
props.put("mail.smtp.port", "587"); // TLS Port
props.put("mail.smtp.auth", "true"); // enable authentication
props.put("mail.smtp.starttls.enable", "true"); // enable STARTTLS
Authenticator auth = new Authenticator() {
// override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
System.out.println("Session created");
sendAttachmentEmail(session,fromEmail, toEmail,"SSLEmail Testing Subject with Attachment", "SSLEmail Testing Body with Attachment");
}
public static void sendAttachmentEmail(Session session,String fromEmail, String toEmail, String subject, String body){
try{
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress(fromEmail));
msg.setReplyTo(InternetAddress.parse(toEmail, false));
msg.setSubject(subject, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
// Create the message body part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(body);
// Create a multipart message for attachment
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
String filename1 = "C:\\TraingWorkspace\\Training\\logs\\DailyLog.zip";
addAttachment(multipart, filename1);
String filename2 = "C:\\TraingWorkspace\\Training\\logs\\DailyLog.log";
addAttachment(multipart, filename2);
// Send the complete message parts
msg.setContent(multipart);
// Send message
Transport.send(msg);
System.out.println("EMail Sent Successfully with attachment!!");
}catch (MessagingException e) {
e.printStackTrace();
}
}
private static void addAttachment(Multipart multipart, String filename) throws MessagingException
{
DataSource source = new FileDataSource(filename);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}

Reading Error in Mail JAVA

I am reading email from gmail.com. i have read some of the mail successfully but after a while i got this,
java.lang.ClassCastException:
javax.mail.internet.MimeMultipart cannot be cast to java.lang.String
at emailIngestion.EmailIngestion.check(EmailIngestion.java:66)
at emailIngestion.EmailIngestion.main(EmailIngestion.java:106).
Actually my requirement is to store content into a variable and then store it in arraylist and then again write it to a file... i have implemented it using this code so if any better ideas are there please share me.
public class EmailIngestion {
static ArrayList<EmailModel> contentList=new ArrayList<EmailModel>();
static ArrayList<EmailModel> metaDataList= new ArrayList<EmailModel>();
public static void check(String host, String storeType, String user,
String password) throws IOException
{
FileWriter fw= new FileWriter("C:\\Users\\Admin\\Desktop\\murtaza_metadata.csv",true);
FileWriter fw1= new FileWriter("C:\\Users\\Admin\\Desktop\\murtaza_content.txt",true);
try {
//create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("pop3s");
store.connect(host, user, password);
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
Message[] messages = emailFolder.getMessages();
int emailNumber;
String mailContent = null,from = null,to = null,mailContentType = null,subject = null;
Date recievedDate= new Date();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("Subject is"+message.getSubject());
subject = message.getSubject();
from = message.getFrom()[0].toString();
mailContentType=message.getContentType();
recievedDate=message.getSentDate();
to=InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
emailNumber=message.getMessageNumber();
metaDataList.add(new EmailModel(from, to, subject, mailContentType, recievedDate,emailNumber));
fw.write(emailNumber+"\001"+from+"\001"+subject+"\001"+recievedDate+mailContentType+"\001"+" \n");
fw.flush();
if(message.isMimeType("multipart/*")){
Multipart multipart = (Multipart) message.getContent();
for (int x = 0; x < multipart.getCount(); x++) {
BodyPart bodyPart = multipart.getBodyPart(x);
mailContent=(String) bodyPart.getContent();
System.out.println(mailContent);
}
}
else{
mailContent=(String) message.getContent();
System.out.println(message.getContent());
}
contentList.add(new EmailModel(mailContent, emailNumber));
fw1.write(emailNumber+","+mailContent+"\n");
}
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username = "abcd#gmail.com";// change accordingly
String password = "******";// change accordingly
check(host, mailStoreType, username, password);
}
}
Thanks in advance
If the services are fluctuating then its definitely not stable. Which version of 1.3 you are using? As you are using one node make sure that you have master and worker services are installed and running. This you can see from your cluster manager. The info from logs is not informative enough to nail down the issue.

Read email content when type is text/html; charset=iso-8859-1

I am reading unread emails from a specific folder like this. Message content type is coming as text/html; charset=iso-8859-1 . How can I get the content as a string ? When I do a toString I am getting something like this com.sun.mail.util.QPDecoderStream#4461c7e3
public Message[] fetchMessages(String host, String user, String password,String folder, boolean read) throws IOException {
try {
Properties properties = new Properties();
properties.put("mail.store.protocol", "imaps");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore();
store.connect(host, user, password);
Folder folderToRead = store.getFolder(folder);
folderToRead.open(Folder.READ_WRITE);
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, read);
Message messages[] = folderToRead.search(unseenFlagTerm);
System.out.println(messages.length);
for(Message message : messages){
System.out.println(getMessageContent(message));
}
}
public getMessageContent(Message message){
String result = "";
if (message.isMimeType("text/html")) {
// My message type is coming as text/html
result = message.getContent().toString();
}
else if (message.isMimeType("text/plain")) {
result = message.getContent().toString();
}
return result;
}
text/plain is an unknown type and was coming as an inputstream. This worked for me
private static String getTextFromMessage(Message message) throws IOException, MessagingException {
String result = "";
if (message.isMimeType("text/plain")) {
result = message.getContent().toString();
} else if (message.isMimeType("multipart/*")) {
MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
result = getTextFromMimeMultipart(mimeMultipart);
}
else{
StringWriter writer = new StringWriter();
IOUtils.copy(message.getInputStream(), writer, "UTF-8");
result = writer.toString();
}
return result;
}

Executing java mail program from unix box machine in which java is installed

I have the below java program which I am executing from eclipse under windows and it is working perfectly. Now I want to create a jar of it which I can make it from eclipse it self by creating a jar option now p, as I want to execute the same program from unix box machine in which java is installed please advise how I will test this same program from unix box machine in which java is installed and jdk is set, shall I go for jar creation process.
public class SSendEmail {
MimeMessage mimeMessage = null;
public static void main(String[] args) throws Exception, IOException, Exception {
String smtpHost = "11.1620.90.520";
String mailSmtpPort = "192381";
String mailTo[] = {"ena#rdbs.com"};
String mailCc[] = {"sena#rdbs.com"};
postEmailForBrokerageNotification(mailTo, mailCc, "k",
"testSubject", "Body123", smtpHost, mailSmtpPort);
}
//Send email for broker post pay email notification
public static void postEmailForBrokerageNotification(String mailTo[], String mailCc[], String from, String subject, String text, String smtpHost, String mailSmtpPort) throws Exception, DocumentException, IOException {
try {
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mail.store.protocol", "imaps");
properties.put("mail.smtp.port", mailSmtpPort);
properties.put("mail.smtp.auth", "false");
//obtaining the session
Session emailSession = Session.getDefaultInstance(properties);
//Enable for debuging
emailSession.setDebug(true);
Message emailMessage = new MimeMessage(emailSession);
if (mailTo != null) {
InternetAddress[] addressTo = new InternetAddress[mailTo.length];
for (int i = 0; i < mailTo.length; i++) {
addressTo[i] = new InternetAddress(mailTo[i]);
}
emailMessage.setRecipients(RecipientType.TO, addressTo);
}
InternetAddress[] addresscc = new InternetAddress[mailCc.length];
for (int i = 0; i < mailCc.length; i++) {
addresscc[i] = new InternetAddress(mailCc[i]);
}
emailMessage.setRecipients(RecipientType.CC, addresscc);
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
emailMessage.setContent(text, "text/html");
//Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, "text/html");
messageBodyPart.setText(text);
// Create a multipart message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// attachment part
MimeBodyPart attachPart = new MimeBodyPart();
String filename = "c:\\sd-Spec_for_Data-Mapping_P3--SARALE_RETURNswap.xls";
DataSource source = new FileDataSource(filename);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(filename);
multipart.addBodyPart(attachPart);
// Send the complete message parts
emailMessage.setContent(multipart);
Transport.send(emailMessage);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException messagingException) {
messagingException.printStackTrace();
throw new Exception(messagingException.getMessage());
}
}
}

Categories