javamail api to access gmail inbox messages - gmail

I have been trying to use the javamail api to read gmail inbox messages. I found the following code on the internet. I'm trying to run this on Eclipse, but it is failing with an "Invalid credentials exception". I have mail.jar, activation.jar, imap.jar and other jar files in the lib directory of the web-app.
Any ideas as to why I am receiving this exception ? Thanks.
javax.mail.AuthenticationFailedException: Invalid credentials n67if632335wep.219
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:665)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at org.mb.mail.MailReader.main(MailReader.java:23)
package org.mb.mail;
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 javax.mail.Store;
import javax.mail.*;
public class MailReader {
public static void main(String args[]) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>", "password");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message);
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}
}

Throw away that code and use this code from the JavaMail FAQ, where you'll also find lots of other helpful tips, including debugging tips.

If you see this exception you are in correct path, just you need to change the mail id or create a new gmail id which will have less security.(for example a primary gmail account is much configured in smartphones and its highly secured with google with Oauth2.0, so that gmail account connection will be blocked by google but when you tried with alternate gmail id or gmail id which not configured in mobile can be easily get connected)
Previously this issue broke my head finally got fixed. Thanks

Related

detect connectivity issue or login failure of ImapMailReceiver

Using Spring integration with Spring mail to connect to IMAP inbox and read emails, I need to detect login failure and network connectivity issues, i cannot find any methods that would let me pull connection status, even errorChannel is not getting any messages nor the logs shows any network connectivity problems
#Bean(name = "getImapMailReceiver")
#Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
ImapMailReceiver getImapMailReceiver(Properties imapConnectionProperties) {
ImapMailReceiver obj = new ImapMailReceiver(imapConnectionProperties.getProperty(IMAP_MAIL_URL_KEY));
obj.setMaxFetchSize(Integer.parseInt(imapConnectionProperties.getProperty(IMAP_MAX_FETCH_SIZE_KEY)));
obj.setJavaMailProperties(imapConnectionProperties);
obj.setShouldDeleteMessages(false);
obj.setAutoCloseFolder(false);
obj.setShouldMarkMessagesAsRead(true);
obj.setSimpleContent(false);
obj.setCancelIdleInterval(10000);
obj.setJavaMailAuthenticator(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(imapConnectionProperties.getProperty("mail.imap.user"),
imapConnectionProperties.getProperty("testpassword"));
}
});
return obj;
}
To catch exceptions from such an ImapIdleChannelAdapter async component, you need to add a even listener for the ImapIdleExceptionEvent.
See more info in docs: https://docs.spring.io/spring-integration/docs/current/reference/html/mail.html#imap-idle-and-lost-connections

azure web app loaded from github repo based on spring boot problem

yesterday i linked my github to an azure web app service
my repo built with rest requests and some of them is working with loading data from firestore based databased , i ran it all on localhost on the tomcat embedded server that comes with spring
,got the web app in the air and my post request which getting resource from firebase , the post request got me an internal 500 server so i check the app insights feature to check what exception i get
java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn't exist.
at com.google.firebase.FirebaseApp.getInstance(FirebaseApp.java:165)
at com.google.firebase.FirebaseApp.getInstance(FirebaseApp.java:136)
my init code for fire base is:
package Model;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.util.Objects;
#Service
public class FBInitialize {
#PostConstruct
public void initialize() {
try {
String fileName = "name of json file with Credential.json";
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(Objects.requireNonNull(classLoader.getResource(fileName)).getFile());
FileInputStream serviceAccount = new FileInputStream(file);
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://qr-database-my data base url")
.build();
FirebaseApp.initializeApp(options);
} catch (Exception e) {
e.printStackTrace();
}
}
i checked on the logs and i did got the request i just getting this exception is anyone ever encounter
this exception ?
by the way on initiazlizeApp method the getIntstance methood is being called.
Edit:
found where the exception was thrown from :
public static FirebaseApp getInstance(#NonNull String name) {
synchronized(appsLock) {
FirebaseApp firebaseApp = (FirebaseApp)instances.get(normalize(name));
if (firebaseApp != null) {
return firebaseApp;
} else {
List<String> availableAppNames = getAllAppNames();
String availableAppNamesMessage;
if (availableAppNames.isEmpty()) {
availableAppNamesMessage = "";
} else {
availableAppNamesMessage = "Available app names: " + Joiner.on(", ").join(availableAppNames);
}
String errorMessage = String.format("FirebaseApp with name %s doesn't exist. %s", name, availableAppNamesMessage);
throw new IllegalStateException(errorMessage);
}
}
}
The problem may be the source code version on github. Please check build.gradle file under android/app folder.
Add the following line:
apply plugin:'com.google.gms.google-services'
Related Posts:
1. How to solve Exception Error: FirebaseApp with name [DEFAULT] doesn't exist?
2. FirebaseApp with name [DEFAULT] doesn't exist
im working with maven , also i figured it out that its has something with the json file with the google credentials location because repackaging the file changing the root content to BOOT-INF so i took the json file content put it in a String and cast it to Inputstream so the Initializeapp and the init would be independent but it still no joy :(
new update:
now i get a different exception I think its about security
java.lang.IllegalStateException: Could not find TLS ALPN provider; no working netty-tcnative, Conscrypt, or Jetty NPN/ALPN available
agian im working with maven and not on android

how I can create a specific phone id a trigger for sending sms?

I want to create an Autoresponder, I want to send SMS just if I
get a phone calls to a specific number.
for example, if my phone ID is 1111 I want that just if someone calls to 1111
he will get SMS
I tried to create a condition for my phone ID but with no success.
this is my code before the condition.
package getstarted;
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.TokenAuthMethod;
import com.nexmo.client.sms.SmsSubmissionResult;
import com.nexmo.client.sms.messages.TextMessage;
public class SendSMS {
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod("zzzzz","yyyyy");
NexmoClient client = new NexmoClient(auth);
TextMessage message = new TextMessage("5555", "9723455555", "Hello from Nexmo!");
SmsSubmissionResult[] responses = client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}
}
}
// We're creating a Java Application:
apply plugin: 'application'
apply plugin: 'java'
// Download dependencies from Maven Central:
repositories {
mavenCentral()
}
// Install the Nexmo Client library:
dependencies {
compile 'com.nexmo:client:2.0.1'
}
// We'll create this class to contain our code:
mainClassName = "getstarted.SendSMS"
When you receive a call to a Nexmo number, a webhook is sent to the answer_url that you configure for that number. You can write some code there to respond to the incoming calls as you wish. In this case you might want to collect the incoming phone number and send an SMS to it. You could also answer and give an automated spoken message letting the user know they'll receive an SMS.
Hope that gives you an idea of the overall workflow - good luck with your project :)

IBM Connections Atom Profile Service

I am trying to get back a profile for myself but I only get back a successful http response...no data. This is the code I am using.
try {
RestClient restClient = new RestClient("https://apps.na.collabserv.com","my.email","my.password");
Response<AtomFeed> responseFeed = restClient.doGet("/profiles/atom/profileService.do").asAtomFeed();
System.out.println(responseFeed.getData().toXmlString());
} catch(Exception e) {
e.printStackTrace();
}
If I try to add a email= to the url I get a 403 forbidden return.
Not really sure what the issue is,
Thanks!

Custom maintenance mode module does not work on Azure Web Role

I've created and registered custom http module to show maintenance message to user after administrator turns on maintenance mode via configuration change.
When I pass request for html it should return custom html loaded from file, but it returns message: "The service is unavailable." I can't find that string in my entire solution. Custom log message from custom maintenance module is written to log4net logs.
... INFO DdiPlusWeb.Common.MaintenanceResponder - Maintenance mode is on. Request rejected. RequestUrl=...
Seems something is miss configured in IIS on Azure. Something intercepts my 503 response. How to fix it?
Module code
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
if (AppConfig.Azure.IsMaintenance)
{
MaintenanceResponder responder = new MaintenanceResponder(context, MaintenaceHtmlFileName);
responder.Respond();
}
}
Interesting part of responder code.
private void SetMaintenanceResponse(string message = null)
{
_context.Response.Clear();
_context.Response.StatusCode = 503;
_context.Response.StatusDescription = "Maintenance";
if (string.IsNullOrEmpty(message))
{
_context.Response.Write("503, Site is under maintenance. Please try again a bit later.");
}
else
{
_context.Response.Write(message);
}
_context.Response.Flush();
_context.Response.End();
}
EDIT: I lied. Sorry. Maintenance module returns the same message for requests that expect json or html.
This answer led me to the solution.
I've added another line to SetMaintenanceResponse method.
_context.Response.TrySkipIisCustomErrors = true;
It works now. Here is more about what it exactly means.

Resources