Cannot fetch Gmail inbox with JavaMail POP - java

I'm trying to fetch unread messages from Gmail inbox with Javamail, but I can't. I only retrieve archived messages (from 2011!!!) and I don't know why or how to do it.
Here is my code:
public List<DefaultMessage> getLatestNthMessages(Integer numberOfMessages) throws Exception {
URLName url = new URLName("pop3", "pop.gmail.com", 995, "",username, password);
Store store = new POP3SSLStore(pullSession, url);
store.connect();
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
SearchTerm st = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
List<Message> msgs = Arrays.asList(inbox.search(st)).stream()
.sorted((m1, m2) -> m2.getMessageNumber() - m1.getMessageNumber())
.limit(numberOfMessages)
.collect(Collectors.toList());
List<DefaultMessage> listOfMessages = new ArrayList<>();
for (Message message : msgs) {
listOfMessages.add(wrapperToMessage(message));
}
return listOfMessages;
}
pullSession is instantiated as follows:
Properties pullProps = new Properties();
pullProps.put("mail.pop3.host", pullHost);
pullProps.put("mail.pop3.username", username);
pullProps.put("mail.pop3.port", pullPort);
pullProps.put("mail.pop3.socketFactory.port", pullPort);
pullProps.put("mail.pop3.socketFactory.fallback", "false");
pullProps.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
pullProps.put("mail.pop3.auth", "true");
pullSession = Session.getInstance(pullProps, null);
pullSession.setDebug(true);

Check your Gmail settings for POP3.
Also, there's lots of things you can improve in your code, although they're not the source of your problem. Start by fixing all the common JavaMail mistakes.
You should not be creating a POP3SSLStore directly. Use the Gmail example code in the JavaMail FAQ.

Related

How to Email execution report in selenium web-driver java without jenkins?

I have tried to use apache common mail API. the code i used is
public static void main(String[] args) throws EmailException {
System.out.print("-------Start------");
// TODO Auto-generated method stub
Email email = new SimpleEmail();
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator(userName, password));
email.setSSLOnConnect(true);
email.setFrom("user#gmail.com");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("myemail#gmail.com");
email.send();
System.out.print("-------End------");
}
but It is saying username and password not accepted however i am providing the correct credentials. When i opened my gmail account , it is showing that it has blocked the sign in attempt. Is there any other way to achieve this?
Please download https://github.com/javaee/javamail/releases
And follow the example below on how to setup Gmail using JavaMail. You dont need any webdriver for this. The javamail jar in your classpath is sufficient.
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendEmailTLS {
public static void main(String[] args) {
final String username = "username#gmail.com";
final String password = "password";
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true"); //TLS
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from#gmail.com"));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse("to_username_a#gmail.com, to_username_b#yahoo.com")
);
message.setSubject("Testing Gmail TLS");
message.setText("Dear Mail Crawler,"
+ "\n\n Please do not spam my email!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
If still having trouble, you might need to use and trust an APP Password.
https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor
Create & use App Passwords
If you use 2-Step-Verification and get a "password incorrect" error when you sign in, you can try to use an App Password.
Go to your Google Account.
Select Security.
Under "Signing in to Google," select App Passwords. You may need to sign in. If you don’t have this option, it might be because:
2-Step Verification is not set up for your account.
2-Step Verification is only set up for security keys.
Your account is through work, school, or other organization.
You turned on Advanced Protection.
At the bottom, choose Select app and choose the app you using and then Select device and choose the device you’re using and then Generate.
Follow the instructions to enter the App Password. The App Password is the 16-character code in the yellow bar on your device.
Tap Done.
Tip: Most of the time, you’ll only have to enter an App Password once per app or device, so don’t worry about memorizing it.
Reference: https://mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

Federated store with repositories from different server

I want to create an abstract repository to a federated store in AllegroGraph.
I can connect to the repositories stored on different server. But when I try to combine them using federate function, it throws an error that it cannot find the repository on the second server.
I found the same question in this link but it doesn't help. Any hints?
This is my code:
AGServer server = new AGServer(SERVER_URL, USERNAME, PASSWORD);
AGServer server2 = new AGServer(SERVER_URL2, USERNAME2, PASSWORD2);
println("Available catalogs: " + server.listCatalogs());
AGRepositoryConnection custCon = server.createRepositoryConnection("repo1", CATALOG_ID, false);
AGRepositoryConnection supCon = server2.createRepositoryConnection("repo2", CATALOG_ID, false);
AGAbstractRepository rainbowRepo = server2.federate(custCon.getRepository(), supCon.getRepository());
rainbowRepo.initialize();
AGRepositoryConnection rainbowConn = rainbowRepo.getConnection();
SailRepository class implements FederatedServiceResolverClient for the federation context, so u can use the class SailRepository to add a federated store with different repositories :
AGServer server = new AGServer(SERVER_URL, USERNAME, PASSWORD);
AGServer server2 = new AGServer(SERVER_URL2, USERNAME2, PASSWORD2);
AGRepository repo1 = server.getCatalog(CATALOG_ID).openRepository("repo1");
AGRepository repo2 = server2.getCatalog(CATALOG_ID).openRepository("repo2");
Federation federation = new Federation();
federation.addMember(repo1);
federation.addMember(repo2);
federation.setReadOnly(true);
SailRepository rainbowRepo = new SailRepository(federation);
rainbowRepo .initialize();
SailRepositoryConnection rainbowConn = rainbowRepo .getConnection(); //for querying and updating the contents of the repository.

How to connect to office365 using IMAPS protocol from Java application

There are few articles out there about this, but non of them worked for me. Basically I have following java code to connect to office 365:
Properties props = new Properties();
props.put("mail.imaps.auth.plain.disable", "true");
props.put("mail.imaps.ssl.enable", "true");
session = Session.getInstance(props, null);
store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, "user#mydomain.com", "psw");
but it fails with LOGIN failed error;
javax.mail.AuthenticationFailedException: LOGIN failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:725)
at javax.mail.Service.connect(Service.java:366)
Also I'm able to login into my account using IMAPS from Thunderbird.
Any pointers to resolve an issue would be appreciated!
This code works for me for outlook I have modified it for use with Office365. I did the research to find the IMAP host for office 365. I hope it helps you.
public static void main(String[] args) throws MessagingException {
MultiPartEmail email = new MultiPartEmail();
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
//extra codes required for reading OUTLOOK mails during IMAP-start
props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.socketFactory.port", "993");
//extra codes required for reading OUTLOOK mails during IMAP-end
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("outlook.office365.com", "some.one#some.org", "mypassword");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
inbox.addMessageCountListener(new MessageCountListener() {
#Override
public void messagesAdded(MessageCountEvent messageCountEvent) {
Message[] messages = messageCountEvent.getMessages();
System.out.println("A message was added, you now have: " + messages.length + " emails");
}
#Override
public void messagesRemoved(MessageCountEvent messageCountEvent) {
}
});
while (true) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
inbox.getMessageCount(); // Keeps connection alive
}
}
As it turned out, office 365 was rejecting connections because of unsupported characters inside the password. Particularly quote character. So, as simple as changing psw fixed my problem.
And following code snippet works just fine:
Properties props = new Properties();
props.put("mail.store.protocol", "imaps");
session = Session.getInstance(props, null);
store = session.getStore();
store.connect("outlook.office365.com", 993, "user#mydomain.com", "psw");
With 'javax.mail', version: '1.5.6'

How to create a new AWS instance using AWS Java SDK

I'm trying to create a new AWS EC2 instance using the AWS Java SDK but getting "Value () for parameter groupId is invalid. The value cannot be empty". Here is my code:
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().getCredentials();
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (~/.aws/credentials), and is in valid format.",
e);
}
ec2 = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(Regions.US_WEST_2)
.build();
}
RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
String ami_id = "ami-efd0428f"; //ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20170414
Collection<String> securityGroups = new ArrayList<>();
securityGroups.add("launch-wizard-1");
securityGroups.add("sg-9405c2f3");
runInstancesRequest.withImageId(ami_id)
.withInstanceType("t2.medium")
.withMinCount(1)
.withMaxCount(1)
.withKeyName("MyKeyName")
.withSecurityGroups(securityGroups);
RunInstancesResult run_response = ec2.runInstances(runInstancesRequest); // fails here!
String instance_id = run_response.getReservation().getReservationId();
Tag tag = new Tag()
.withKey("Name")
.withValue(tfCompanyName.getText());
Collection<Tag> tags = new ArrayList<>();
tags.add(tag);
CreateTagsRequest tag_request = new CreateTagsRequest();
tag_request.setTags(tags);
CreateTagsResult tag_response = ec2.createTags(tag_request);
String s = String.format("Successfully started EC2 instance %s based on AMI %s",instance_id, ami_id);
System.out.println(s);
Any suggestions?
You might need to add a VPC details also .
PrivateIpAddresses ,Monitoring are among other required fields.
I would recommend you to try creating EC2 Instance manually using AWS Console and see what are the required parameters it is asking?

Running JavaMail API in Gradle Project on Eclipse

I have a Gradle project in my Eclipse IDE and I need to be able to send an e-mail receipt as part of a school project. I looked at this link http://www.tutorialspoint.com/java/java_sending_email.htm to try and create the most basic e-mail. I've tried the "sending a simple e-mail" example and I got this as my error:
Usage - java org.mortbay.jetty.Main [<addr>:]<port>
Usage - java org.mortbay.jetty.Main [<addr>:]<port> docroot
Usage - java org.mortbay.jetty.Main [<addr>:]<port> -webapp myapp.war
Usage - java org.mortbay.jetty.Main [<addr>:]<port> -webapps webapps
Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port>
Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port> docroot
Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port> -webapp myapp.war
Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port> -webapps webapps
I'm guessing I don't have the JavaMail API and Java Activation Framework (JAF) properly installed. I've followed some guides on how to do that. What I've done was right click gradle project -> Properties -> Java Build Path -> Libraries tab -> Add External JARs.. And I added the JAF and JavaMail jar files (activation-1.1.1.jar and mail-1.4.5.jar). I also added
compile group: 'javax.mail', name: 'mail', version: '1.4.5'
compile group: 'javax.activation', name: 'activation', version: '1.1.1'
to my build.gradle file. Any help on how to get this working would be greatly appreciated.
Here is the code I used.
// File Name SendEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "abcd#gmail.com";
// Sender's email ID needs to be mentioned
String from = "web#gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
You have to give proper settings to send email. like
String host = "localhost"; // instead of localhost you have to give your hostname.
If you want to send mail via gmail, use the following code:
SendEmail.java
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail{
public static void main(String[] args) {
final String username = "username#gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Welcome Message");
Transport.send(message);
System.out.println("Mail Sent Successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}

Categories

Resources