Need help about "Get Attachment File Name" Tutorial from Java2s.com - java

i try the tutorial Get Attachment File Name from Java2s.com.
What i'm doing is to read email from the Outlook Web Access Light.
If i put the url address of the Outlook Web Access Light, i have the error:
Exception in thread "main" javax.mail.NoSuchProviderException: No provider for http
at javax.mail.Session.getProvider(Session.java:455)
at javax.mail.Session.getStore(Session.java:530)
at javax.mail.Session.getFolder(Session.java:602)
at MainClass.main(MainClass.java:19)
Java Result: 1
I don't understand the line :
("protocol://username#host/foldername");
here is the code:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
public class MainClass {
public static void main(String[] args) throws Exception {
URLName server = new URLName("protocol://username#host/foldername");
Session session = Session.getDefaultInstance(new Properties(), new MailAuthenticator());
Folder folder = session.getFolder(server);
if (folder == null) {
System.out.println("Folder " + server.getFile() + " not found.");
System.exit(1);
}
folder.open(Folder.READ_ONLY);
Message[] messages = folder.getMessages();
for (int i = 0; i < messages.length; i++) {
System.out.println(messages[i].getSize() + " bytes long.");
System.out.println(messages[i].getLineCount() + " lines.");
String disposition = messages[i].getDisposition();
if (disposition == null){
; // do nothing
}else if (disposition.equals(Part.INLINE)) {
System.out.println("This part should be displayed inline");
} else if (disposition.equals(Part.ATTACHMENT)) {
System.out.println("This part is an attachment");
String fileName = messages[i].getFileName();
System.out.println("The file name of this attachment is " + fileName);
}
String description = messages[i].getDescription();
if (description != null) {
System.out.println("The description of this message is " + description);
}
}
folder.close(false);
}
}
class MailAuthenticator extends Authenticator {
public MailAuthenticator() {
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
}
Thank you for your support
have a nice day

Given the error message I really think javaMail is expecting for protocol one of "smtp:" or "imap:" or "pop3:", because it is the way it constructs its session.
I don't think it will ever work with a web access, you have to get the address of the pop3/imp/smtp server the web interface connects to.

I'm not sure but "protocol://username#host/foldername" seems to describe a format rather than a real url, i.e. it tells you to add a protocol, a user name, a host and a folder like "http://Thomas#stackoverflow.com/need-help-about-get-attachment-file-name-tutorial-from-java2s-com" (just an example of how it might look like, this particular url is not likely to work/exist/whatever :) ).

Related

javax.mail.AuthenticationFailedException: [AUTH] Web login required

I build an application using Java to read emails. And It worked without any errors past days. But suddenly today came up an error like this.
javax.mail.AuthenticationFailedException: [AUTH] Web login required: https://support.google.com/mail/answer/78754
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:207)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at MailReader.readMail(MailReader.java:44)
at MailReader.run(MailReader.java:32)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
I can't figure out how to fix this. I didn't put 2-way authentication. And also I put less secure app allowed. So I can't figure out what is wrong. Anybody can help me? I greatly appreciate that.
Here is the code I am using,
String host = "pop.gmail.com";
String username = "somename#gmail.com";
String password = "password";
Properties prop = new Properties();
Session session = Session.getInstance(prop, null);
Store store = session.getStore("pop3s");
store.connect(host, username, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
The error was due to an error at Google, which caused POP3 services to work incorrectly. It was fixed after 2 days.
Could not find official statement, only forum posts. Related sources:
1, 2, 3
My working snippet looks like below:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
public class CheckingMails {
public static void check(String host, String user, String password)
{
try {
// create properties field
Properties properties = new Properties();
properties.put("mail.pop3s.host", host);
properties.put("mail.pop3s.port", "995");
properties.put("mail.pop3s.starttls.enable", "true");
// Setup authentication, get session
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
// session.setDebug(true);
// create the POP3 store object and connect with the pop server
Store store = session.getStore("pop3s");
store.connect();
// create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
// close the store and folder objects
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) {
String host = "pop.gmail.com";
String username = "abc#gmail.com";// change accordingly
String password = "*****";// change accordingly
check(host, username, password);
}
}
My problem was that the same code was working on local but not on the remote cloud (Bitbucket pipeline) although I set the less secure enable. I solved it by enabled 2 step verification and create an app password. Then used this app password instead of the normal password in the code.
You can check the following link as well: https://docs.maildev.com/article/121-gmail-web-login-required-error---answer78754-failure

Java IMAP endless loop while writing to EML

We got a serious problem in our system which is processing mails from IMAP and saving it as EML. Thing is, everything works in production but not on dev machine anymore, therefore we cannot make any fixes or further development. This is kind of strange, because also this example does not work:
package com.test;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
public class ReadMail {
public static void main(String args[]) throws Exception {
String host = "mail";
String user = "xxx";
String password = "zzz";
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore("imap");
store.connect(host, user, password);
Folder folder = store.getFolder("a");
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println(message[i].getSentDate());
System.out.println(message[i].getFrom()[0]);
System.out.println(message[i].getSubject());
try (OutputStream out = new FileOutputStream("something"+i+".eml")) { // fix the name of course
message[i].writeTo(out);
}
}
folder.close(true);
store.close();
}
}
In writeTo it makes endless loop and creates file which grows until the disk is full. This is from com.sun.mail.imap.IMAPMessage
/**
* Write out the bytes into the given OutputStream.
*/
public void writeTo(OutputStream os)
throws IOException, MessagingException {
if (bodyLoaded) {
super.writeTo(os);
return;
}
InputStream is = getMimeStream();
try {
// write out the bytes
byte[] bytes = new byte[16*1024];
int count;
while ((count = is.read(bytes)) != -1)
os.write(bytes, 0, count);
} finally {
is.close();
}
}
It will never exit from the while clause. Should it be some error on the Postfix side? The mail is multipart MIME message and the EML created are just multiple copies of EML. Only difference between prod and dev machine is HW. JDK8 is the same. Any hints?
Java mail API used:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.6</version>
</dependency>
UPDATE SOLVED: ESET Nod32 Antivirus software intercept the IMAP traffic in that way, that the buffer never returns -1! After disabling ESET Mail, everything works.

Java : Using Javamail to read email

I've been working on a program, that's suppose to use javamail, to read through an inbox, and if an email contains a specific String, it should be opened.
First off, this is my first time trying to use this javamail api - I'm pretty sure that my properties are all messed up - Can anyone give me at tip on correctly setting up properties for javamail?
Secondly, it seems like i can connect via the API, but if I try to search for subjects AND the subject is null, I get a null pointer exception - If I however don't try to match the subject with "Ordretest", I get no nullpointer - Any tips would be a great help :)
package vildereMail;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.search.FromTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
public class vildereMail {
public boolean match(Message message) {
try {
if (message.getSubject().contains("Ordretest")) {
System.out.println("match found");
return true;
}
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
};
public static void main(String[] args) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
props.put("mail.imap-mail.outlook.com.ssl.enable", "true");
props.put("mail.pop3.host", "outlook.com");
props.put("mail.pop3.port", "995");
props.put("mail.pop3.starttls.enable", "true");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap-mail.outlook.com", "myEmail#live.dk", "MyPassword");
session.setDebug(true);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
SearchTerm sender = new FromTerm(new InternetAddress("myMail#live.dk"));
Message[] messages = inbox.search(sender);
System.out.println(messages);
for (int i = 0 ; i < messages.length ; i++) {
System.out.println(messages[i].getSubject());
if (messages[i].getSubject().equals(null)) {
System.out.println("null in subject");
break;
}
else if (messages[i].getSubject().contains("Ordretest")){
System.out.println("1 match found");
}
else {
System.out.println("no match");
}
}
System.out.println("no more messages");
store.close();
} catch (Exception mex) {
mex.printStackTrace();
}
}
}
Without knowing on which line you get the NPE (Null Pointer Exception) I guess it occurs here:
if (messages[i].getSubject().equals(null))
If getSubject() returns null and you try to do .equals() it will throw a NPE (because you try to invoke a method).
So try to rewrite it to (assuming your message object can't be null):
if (messages[i].getSubject() == null)
Where to start...
Have you found the JavaMail FAQ?
You can get rid of all the property settings because they're doing nothing since you're using the "imaps" protocol, not the "pop3" protocol.
As others have explained, the getSubject method might return null, so you need to check for that.

Using JavaMail to read the mail

I am getting this error when tried to read mail using JavaMail. please let me know how to resolve this error. I have added activation.jar and mail.jar into eclipse.
DEBUG POP3: server doesn't support TOP, disabling it
javax.mail.AuthenticationFailedException: Command is not valid in this state.
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:174)
at javax.mail.Service.connect(Service.java:291)
at javax.mail.Service.connect(Service.java:172)
at library.VerifyEmail.main(VerifyEmail.java:40)
Below is the code I am trying:
package library;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import com.sun.mail.pop3.POP3Store;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.SubjectTerm;
import javax.activation.*;
import java.io.*;
public class VerifyEmail {
public static void main(String[] args) throws Exception {
// SUBSTITUTE YOUR ISP's POP3 SERVER HERE!!!
String host = "myhost";
// SUBSTITUTE YOUR USERNAME AND PASSWORD TO ACCESS E-MAIL HERE!!!
String user = "myuser";
String password = "mypass";
// Get a session. Use a blank Properties object.
Session session = Session.getInstance(new Properties());
try {
// Get a Store object
Store store = session.getStore("pop3");
store.connect(host, user, password);
// Get "INBOX"
Folder fldr = store.getFolder("INBOX");
fldr.open(Folder.READ_WRITE);
int count = fldr.getMessageCount();
System.out.println(count + " total messages");
// Message numebers start at 1
for(int i = 1; i <= count; i++) {
// Get a message by its sequence number
Message m = fldr.getMessage(i);
// Get some headers
Date date = m.getSentDate();
Address [] from = m.getFrom();
String subj = m.getSubject();
String mimeType = m.getContentType();
System.out.println(date + "\t" + from[0] + "\t" +
subj + "\t" + mimeType);
}
}catch (MessagingException ioex) {
ioex.printStackTrace();
}
}
}
When you're getting the javax.mail.AuthenticationException it means that your application is unable to authenticate to the mail server.
One possible reason for this might be that an SSL certificate of the mail server is missing from the client keystore.
According to microsoft: For exchange 2010, by default, the server would need the client use ssl for pop3.
Without ssl the server responds with "ERR command is not valid in this state."
Here's how to use javamail with ssl - Javamail and Gmail Pop3 SSL
DEBUG POP3: server doesn't support TOP, disabling it
this message can be disable by updating the java mail jar version to 1.4.4

java flickr and flickrj download user pictures

Hi I am new to flickrj library.
Have foundational java knowledge though.
The project that I am working on requires me to authenticate into flickr and then download geo-tagged images into a folder in local hard drive. The program will be Desktop application program.
I am approaching the program by breaking down into 3 steps.
1.Proper authentication to be completed.(which i have succeeded)
2.Try to download all the photos that user has when authenticated.
3.Try to alter the code a little so that it will only download geo-tagged images.
My problems is on step 2. I cant download logged-in user images let alone geo-tagged ones.
I am trying the code provided by Daniel Cukier here
But I am running into problem.
My netbeans simply strike off at the line 77 on .getOriginalAsStream() part, with the error "java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.io.ByteArrayOutputStream.write"
From my understanding netbeans striking off a line means , it is depreciated but shouldnt it still work? What is holding this whole problem back?
I have tried researching and basically I have to admit , it is beyond my capability to trouble shoot. If anyone has any idea on what i am doing wrong , I would be so grateful.
Ps: I am not looking to be spoon fed but please answer me in idiot-friendly way as I am still a student and my java isn't the greatest.
This code is what I have so far.
import com.aetrion.flickr.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Properties;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.util.IOUtilities;
import java.io.*;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
public class authenticate {
Flickr f;
RequestContext requestContext;
String frob = "";
String token = "";
Properties properties = null;
public authenticate() throws ParserConfigurationException, IOException, SAXException {
InputStream in = null;
try {
in = getClass().getResourceAsStream("/setup.properties");
properties = new Properties();
properties.load(in);
} finally {
IOUtilities.close(in);
}
f = new Flickr(
properties.getProperty("apiKey"),
properties.getProperty("secret"),
new REST()
);
Flickr.debugStream = false;
requestContext = RequestContext.getRequestContext();
AuthInterface authInterface = f.getAuthInterface();
try {
frob = authInterface.getFrob();
} catch (FlickrException e) {
e.printStackTrace();
}
System.out.println("frob: " + frob);
URL url = authInterface.buildAuthenticationUrl(Permission.DELETE, frob);
System.out.println("Press return after you granted access at this URL:");
System.out.println(url.toExternalForm());
BufferedReader infile =
new BufferedReader ( new InputStreamReader (System.in) );
String line = infile.readLine();
try {
Auth auth = authInterface.getToken(frob);
System.out.println("Authentication success");
// This token can be used until the user revokes it.
System.out.println("Token: " + auth.getToken());
System.out.println("nsid: " + auth.getUser().getId());
System.out.println("Realname: " + auth.getUser().getRealName());
System.out.println("Username: " + auth.getUser().getUsername());
System.out.println("Permission: " + auth.getPermission().getType());
PhotoList list = f.getPhotosetsInterface().getPhotos("72157629794698308", 100, 1);
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Photo photo = (Photo) iterator.next();
File file = new File("/tmp/" + photo.getId() + ".jpg");
ByteArrayOutputStream b = new ByteArrayOutputStream();
b.write(photo.getOriginalAsStream());
FileUtils.writeByteArrayToFile(file, b.toByteArray());
}
} catch (FlickrException e) {
System.out.println("Authentication failed");
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
authenticate t = new authenticate();
} catch(Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}
You are correct in your interpretation of the strikeout that getOriginalAsStream() is deprecated. It looks like you might want to rework your code to use PhotosInterface.getImageAsStream(), passing the ORIGINAL size as one of the arguments.
To adjust NetBeans' behavior with respect to deprecated methods, you can follow the link recommended by #AljoshaBre as well as this one.
If you want download all your photos from Flickr, this is possible if you have a mac computer.
Download Aperture program on Apple Store and install it.
After to install, open the Aperture.
Go on preferences.
Click on 'Accounts' tab.
Click on plus sign (+) on bottom left to add a photo service.
Add the Flicker option.
Follow the login and authorization instructions.
Done! All your photos will be synchronized in you aperture library locate on ~/images/
I hope I have helped.

Categories

Resources